Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, September 2, 2013

Anonymous Types in C#




n this article, we will learn how to use anonymous types in C#.

  1. Anonymous types were introduced in C# 3.0.
  2. These are data types generated on the fly at runtime.
  3. These data types are generated by the compiler rather than explicit class definition.

Program.cs

using System;
using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace
ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            var MyAnonClass = new
            {
                Name = "Scott",
                Subject  = "ASP.Net"
            };
            Console.WriteLine(MyAnonClass.Name);
            Console.Read();
        }
    }
}

Outputanan1.gif

A class without a name is generated and assigned to an implicitly typed local variable.
How does it work internally?
  1. For anonymous type syntax, the compiler generates a class.
  2. Properties of the class generated by the complier are value and data type given in the declaration.
  3. Intellisense supports anonymous type class properties.

    anan2.gif
  4. Properties of one anonymous type can be used in the declaration of other anonymous types.
anan3.gif

Program.cs
using System;
using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace
ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            var MyAnonClass = new
            {
                Name = "Scott",
                Subject = "ASP.Net"
            };
            Console.WriteLine(MyAnonClass.Name);
            Console.Read();
            var SecondAnoynClass = new
            {
                info = MyAnonClass.Name + MyAnonClass.Subject
            };
            Console.WriteLine(SecondAnoynClass.info);
            Console.Read();
        }
    }
}
Output

anan5.gif

Thursday, August 29, 2013

Free E-Book: TypeScript for C# Programmers




Due to the popularity of the open web, JavaScript is becoming an essential language and since 2009 it has been running on servers too thanks to NodeJS. The problem is that due to JavaScript's dynamic type system, it is hard to create great tooling around the language such as sensible auto-completion, refactoring support, type-checking and modularisation.
TypeScript is an open source lanaguage from Microsoft that solves this problem by introducing an optional type system and class-based object-orientation, which make great tooling for large applications possible.
TypeScript let's you write JavaScript that is robust enough for the enterprise and that can run in any browser, on any host and on any operating system.

Free download

Download this book FREE (PDF)

Tabel of Contents

  • Compiling or Transpiling

  • Language Features

    • TypeScript Files
    • Types
    • Modules, Classes and Interfaces
    • Functions
    • Enumerations
    • Generics
  • Structural Typing

  • Access Modifiers

  • Memory Management

    • Releasing Resources
  • Exceptions

  • Arrays

  • Dates

    • Now
    • Date Methods
  • Events

    • Mouse Events
    • Keyboard Events
    • Object Events
    • Form Events
    • Custom Events
    • Running Order
  • Framework

  • Creating Definitions

    • Dynamic Declarations
    • Type Declarations
  • Useful Tricks

    • Obtaining Runtime Types
    • Extending Native Objects

Wednesday, August 28, 2013

5 Tips to Improve Your C# Code



Tip 1: StringBuilder consumes less memory than String

In my previous article I have shown how slow string is in a scenario of long concatenation operations. And here we will see a memory allocation graph of String and StringBuilder. Let me show that in action. The following is my code to do same operation with both a string and a StringBuilder.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.IO;using System.Net;using System.Net.NetworkInformation;using System.Threading;using System.Globalization;using System.Data.SqlClient;namespace Test1
{
    public class
Test1    {
        string Name ;
        public void Process()
        {
            Name = Name + "A";
        }
    }
    public class
Test2    {
        StringBuilder sb = new StringBuilder();
        public void Process()
        {
            sb.Append("A");
        }
    }
    class
Program    {
        static void Main(string[] args)
        {
            Test1 t = new Test1();
            t.Process();
            Test2 t1 = new Test2();
            t1.Process();
        }
    }
}


And here is the memory allocation graph from execution of the code.

image1.gif

Here from the main function we are calling the two functions Process(); though they both have the same name they belong to different classes and Test1.Process is handling string data whereas Test2.Process() is handling string builder data. And in the allocation graph we can see the String handling function consumes 94% resource of the Main () function whereas Process() in the Test2 class that deals with StringBuilder only consumes .21 % of the resources of the Main() function.

So, in a single line the conclusion is "Always use StringBuilder when you want to concatenate strings many times".

Tip 2: If possible use a static function

Yes, if possible try to implement a static function because static objects (both function and data) does not belong to any object of a particular class. It's common to all. So if you do not create an object then there is no question of memory consumption. In the following I am showing one example of a static function and static class. And have a look at the IL code.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.IO;using System.Net;using System.Net.NetworkInformation;using System.Threading;using System.Globalization;using System.Data.SqlClient;namespace Test1
{
    public static class
mySclass    {
        public static void Print()
        {
            Console.Write("Hello");
        }
    }
    public class
myNclass    {
        public static void Print()
        {
            Console.Write("Hello");
        }
    }
    class
Program    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 1000; i++)
            {
                mySclass.Print();
                myNclass.Print();
            }
        }
    }
}
The IL code is in the left hand side and in the right hand the top few memory consuming classes, taken by the CLR profiler. I cannot show the full screenshot of the CLR profiler due to space consumption. But believe me (Ha..Ha) there is no memory allocation of a static class or function.

image2.gif

So, in a single line the conclusion is "If possible try to create a static function and invoke with the class name rather than invoking the general function by object name".

Tip 3: String format VS String concatenation

In the first point I was showing how a string consumes more resources than a StringBuilder. In this point I will compare formatted output with string concatenation. In the first function I am using a format specification to print formatted output (basically I am concatenating a string). And in another function I am using the (+) operator to concatenate a string, as in the following:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.IO;using System.Net;using System.Net.NetworkInformation;using System.Threading;using System.Globalization;using System.Data.SqlClient;namespace Test1
{
    class
Test    {
        public void Format()
        {
            int a = 100;
            Console.WriteLine("{0}AND{1}", a, a);
        }
        public void Concatination()
        {
            int a = 100;
            Console.WriteLine(a + "AND" +a );
        }
    }
    class
Program    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Format();
            t.Concatination();
            Console.ReadLine();
        }
    }
}
And in memory allocation we will see:

image3.gif

That function that was printing a string using format is consuming 57 % of the resources and the function that simply concatenates two strings consumes 30 % resources of the main function. So we can clearly see if we use string concatenation rather than output formatting we can save our system resources.

Tip 4: Which class consumes maximum resources in an empty program?

First of all this point does not recommend any best practice technique. I just want to show that if we run one empty program (with just a Main() function in it) then how much memory is allocated? The following is my very simple program.
using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace
Test1
{
    class
Program    {
        static void Main(string[] args)
        {
        }
    }

}
Yes, I did not write anything in this program. Let's look at the memory map.

image4.gif

Here I am showing top six resource-consuming classes relevant to the scenario of when we run an empty program. It's clearly visible that the String class is taking the most resources (25 % of the whole). Now for a question. In a program that we never use a string, why does the string class consume the most resources? If we look at the call graph of this program then we will see in the main function many internal functions are being called and most of them are taking an argument as a string and to generate those arguments the CLR is usually using the String class. If you have different opinion please use comment box as in the following.

Tip 5: Implement a using block to manage memory

It's a best practice to always implement a using block to manage resources. And practically we can prove that a using block consumes less memory than without a using block statement. We know that if we implement a using block out code size might be larger because the using block internally creates a try catch in IL code but once it is implemented in IL code during runtime it efficiently handles system memory. To demonstrate this I have written a simple program as in the following.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.IO;using System.Net;using System.Net.NetworkInformation;using System.Threading;using System.Globalization;using System.Data.SqlClient;namespace Test1
{
    class
Test    {
        public void Test1()
        {
             StreamWriter wr = new StreamWriter(@"D:\text.txt");
        }
        public void Test2()
        {
             using (StreamWriter wr = new StreamWriter(@"D:\abc.txt"))
             {
             }
        }
    }
    class
Program    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Test1();
            t.Test2();
        }
    }
}

And in the output section I have combined three output screens.

image5.gif

In the allocation graph we see that the using block is consuming less resources than without the using block because if we implement a using block, the program can manage memory efficiently.


Thursday, August 15, 2013

vs-android: Developing for Android in Visual Studio



About six weeks ago I moved into that club which everyone else seemed to be part of, but not me. I joined the ranks of smartphone owners! No more 90′s flip-phone; I picked up a recent-ish Android handset. I’d never really been too into the whole concept of smartphone, but was starting to feel a little left behind. I must say that after those few weeks I’m sold, these things are pretty cool.
So, what’s a programmer to do? I think I may have actually downloaded the Android SDK before I even received the phone. Yeah, just a little bit eager! It’s actually the second handheld device I’ve tried to code on. The first being the Tapwave Zodiac, also with an arm processor and touchscreen. I never really got anything worthwhile going on it, my excuse being a job hunt and subsequent move to the United States. But nonetheless, it was a fun little handheld to code for. I was certainly looking forward to coding on a much more popular device.


Total Eclipse of the IDE

Now if you’ve ever tried to write anything for the Android, you’ll know the preferred development environment is Eclipse. If you’re writing your stuff completely in Java, you have everything you’d ever need in Eclipse. It seems to do all the nice syntax highlighting, and intellisense-like functionality that Visual Studio offers. Of course the shortcut keys are completely wrong, and must have been setup by a madman ;) , but it does seem a pretty good IDE to develop in. Better yet, it’s free!
But is it for me? Nah. It’s not for me.
I just couldn’t get on with it. Primarily I want to write my code in C/C++ too. So I started to convince myself that I needn’t bother with Eclipse. I can get all the highlighting and quick-reference stuff in Visual Studio, and I could run batch files to build my code. After all, with C++ under Eclipse you still have to install Cygwin and effectively build from the command-line. (or setup batch/makefiles as you would with Visual Studio).



eclipse



I’ve used Visual Studio for a very long time now, since it’s older guise as simply: ‘Visual C++’. Was version 4.0 I think that I started with, when I moved from DOS to Windows programming. Now it’s my primary coding IDE; I’ve used it at both games companies I’ve worked at in the past decade. It’s an odd one to admit, but it’s too hard to let the thing go.

Makefile Project

So I set off and started a ‘Makefile Project’ in Visual Studio. I could update the system include paths under Visual Studio 2010 (something I think was trickier with earlier versions, or at least not set on a per-project basis, I forget). This meant I’d get properly working intellisense of the Android NDK headers, the ‘External Dependencies’ list in my solution was all completely correct too. All in all, a pretty nice setup.
I put together a batch file, which invoked a cygwin session running ‘ndk-build’. I then setup some further ones which would build the entire package using ‘ant’, and then install and run the application on the Android device connected to my PC. Not much to argue with here. For someone who was longing for Visual Studio back, after a few days with Eclipse. It was lovely.
If you want to try the makefile method, take a look at this website:
His method is a little cleaner than the one I used, my batch/script files were hard-coded messes of experimentation. Check out the debugging article on his page too, he’s got a way of using WinGDB to debug Android NDK code in Visual Studio. It’s awesome.

What about when it gets big?

Unfortunately Android’s NDK build scripts under Cygwin on Windows, isn’t exactly the performer. When your file count gets into triple figures the initial dependency checks take an age. I also wasn’t too enamored with not knowing what was passed to my compiler. You get a limited set of proprietary settings you can change in your makefile, but it did feel like a black box.



ndk-build



Coming from a console background, I like to know what my debug and release builds actually are. I also like to setup further build variants too… Usually one specific to profiling the game, essentially release with some limited modules enabled to do the profiling. The other major one would be a variant of my debug build, with asserts on but the optimization cranked up to max.
So it did feel a little confining. My realization about the build slowdowns with lots of files came when I attempted to integrate third-party code… Specifically what I’m wanting to use is the Irrlicht engine. It’s a well-structured open source rendering engine. Very versatile, and runs on a variety of platforms. Android included, of course.
Runing ndk-build, the thing would sit there for well over a minute before even starting to compile files. I’ve a recent i7-based laptop too, so it’s no slouch. I had an itching to try and delve into a more integrated method of building with Visual Studio, and that tipped the balance for me.

Enter MSBuild

With Visual Studio 2010 Microsoft made a radical change to the way their C++ environment worked. They moved over the entire thing to use MSBuild. Having worked with a certain non-Microsoft gaming console, you could see that they had to do a little hoop-jumping in previous versions of Visual Studio. Integrating custom compilers with the older versions really appeared to be quite a task. With VS2010, it had been hinted on some preview posts from Microsoft that this would be far easier.
Unfortunately though when I started to look into this, I found next to no information on the web about it. Well, really I found absolutely nothing in the end. I found a couple of questions on stackoverflow.com about the same subject, but with no answers. I ended up searching through the Visual Studio directories to find the existing scripts for Microsoft’s compiler. From there I duplicated the directory layout and began tinkering with setting up a new platform.
I’d never used MSBuild before this. It was completely new to me, never even seen a MSBuild file before. I hear some game companies use it, but ours certainly doesn’t. I can definitely recommend it though, it’s very powerful and flexible. It does have quite a learning curve, and Google searching for documentation can lead you to very bad explanations of how it works. If you’re at all interested in it, I recommend this book:
As well as being a very good guide to MSBuild, it actually had a small chapter about exactly what I was trying to do! Something I couldn’t find at all with Google. Unfortunately I picked the book up after I’d done the majority of my scripting, but it at least showed me I was barking up the right tree.

vs-android



vs-android



So, vs-android. Once I’d gotten all the features I wanted, and all the bugs I could find ironed out, I decided to release it as open-source. The regular download package just consists of a collection of MSBuild scripts, which need to be copied within a certain sub-directory of your Visual Studio installation.
Alongside the scripts is a single DLL file. When you’re working with MSBuild, you can code up custom tasks in a .NET language, such as C#. The header dependency scanning code lives here, which invokes gcc to find all the headers that the c/cpp files would be dependent on. As well as some other command-line switch manipulation code. The full source to the C# DLL is up on my Google code page.


vs-android


You can download vs-android here:

There’s full documentation on those pages too. Along with a step-by-step example of getting Android’s ‘san-angeles’ sample app compiling and linking. The Google Code page also contains more technical info about the implementation, if you’re interested. There’s a link on the main page to ‘tech notes’, which expands on some of the points I’ve touched on here.