Friday, May 23, 2008

Automatic Properties

Automatic Properties
If you are already c# developer and you are developing classes with properties as shown below.


public class Student

{

private string _firstName;
private string _lastName;
private int _age;

public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}

public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}

public int Age
{

get { return _age;}
set {_age = value;}
}

}

as mention above we are not applying any logic in the getters/setters of our properties but instead we just get/set the value directly to a field. so there is question in our mind that instead of that why not just use fields instead of properties? There are losts of downsides to exposing public fields.

Few problems are mention below.

1) You can't easily data bind against fields

2) If you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters) without recompiling any assemblies compiled against the old class.

The new C# compiler that ships in "Orcas" has new feature named "Automatic Properties". Automatic properties allow you to avoid having to manually declare a private field and write the get/set logic -- instead the compiler can automate creating the private field and the default get/set operations for you.

As above example I have to write just as bellow.

public class Student
{

public string FirstName { get; set; }
public string LastName { get; set; }

public int Age { get; set; }

}

When the C# "Orcas" compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for that within class, and implement a public getter and setter property implementation to it. The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our first (more verbose) implementation above. This means that unlike public fields I can in the future add validation logic within my property setter implementation without having to change any external component that references my class.

Above code some what like abstract property inside the abstract class but it is different than the code mention below.

public abstaract class Student
{

public abstract string FirstName { get; set; }

}

Automatic private field generated by complier can not be viewed directly it can be seen only in the ILDASM.exe.

Limitations of Automatic Properties

1) You can not define read-only and write only properties.

// Read-only property? Error!

public int MyReadOnlyProp { get; }

// Write only property? Error!

public int MyWriteOnlyProp { set; }

Above code will give you compile time error it must have both read and write properties.

2) As mention that private backing field for the public property is generated by the compiler run time. Developer can use only the public property in his/her code. He/she can’t user private field in the code. In below example I have custom class which implements ToString() which can't use private field.

class Employee

{

public string FirstName { get; set; }
public override string ToString()
{

// No access to the private member in the defining
// class. Must use properties!
// you can not use here private filed since it is not visible here it will be
// generated by compiler

return string.Format("Employee First Name = {0}", FirstName);

}

}

Restrict Access on Automatic Properties:

As In the C# 2.0 we were able to set the access modifier to getter ans setter in automatic property it is also possible.

// Anyone can get the FirstName value, but
// only the defining type and the children can set it.

public int FirstName

{

get { return firstName; }
protected set { firstName = value; }

}

This same possibility is allowed using automatic property syntax as follows:

public string FirstName { get; protected set; }

Of course, with this update, the Main() method would now generate a compiler error when attempting to assign the value of the FirstName property:

static void Main(string[] args)

{

...
// Error! Setting the
FirstName is only possible
// from within the Employee type or by a child type!

e. FirstName = "Tejas";

// Getting the value is still OK.

Console.WriteLine("Your FirtName is {0}? ...", e.FirstName);

Console.ReadLine();

}

Regarding Automatic Properties and Default Values

When you use automatic properties to encapsulate numerical or Boolean data, you are able to use the auto generated type properties straightaway within your code base, as the hidden backing fields will be assigned a safe default value that can be used directly. However, be very aware that if you use automatic property syntax to wrap a reference type, the hidden private reference type will also be set to a default value of null:

class EmployeeCollection

{

// The hidden int backing field is set to zero!
public int NumberOfEmployee { get; set; }

// The hidden Employee backing field is set to null!
public Employee GEmployee { get; set; }

}

Given C#’s default values for field data, you would be able to print out the value of

NumberEmployee as is (as it is automatically assigned the value of zero), but if you directly invoke Employee, you will receive a null reference exception:

static void Main(string[] args)

{

...

EmployeeCollection e = new EmployeeCollection ();

// OK, prints defualt value of zero.

Console.WriteLine("Number of Employee: {0}", e.NumberOfEmployee);

// Runtime error! Backing field is currently null!

Console.WriteLine(e.GEmployee. FirstName);

Console.ReadLine();

}

Given that the private backing fields are created at compile time, you will be unable to make use of C# field initialization syntax to allocate the reference type directly with the new keyword. Therefore, this work will need to be done with type constructors to ensure the object comes to life in a safe manner. For example:

class EmployeeCollection

{

// The hidden backing field is set to zero!
public int NumberOfEmployee { get; set; }

// The hidden backing field is set to null!
public Employee GEmployee { get; set; }

// Must use constructors to override default
// values assigned to hidden backing fields.

public EmployeeCollection ()
{

GEmployee = new Employee ();
NumberOfEmployee = 1;
}

public EmployeeCollection (Employee emp, int number)

{

GEmployee = emp;
NumberOfEmployee = number;
}

}

As you most likely agree, this is a very nice extension to the C# programming language, as you can define a number of properties for a class using a streamlined syntax. Be aware of course that if you are building a property that requires additional code beyond getting and setting the underlying private field (such as data validation logic, writing to an event log, communicating with a database, etc.), you will be required to define a “normal” .NET property type by hand. C# 2008 automatic properties never do more than provide simple encapsulation for an underlying data type.

Wednesday, May 21, 2008

Implicitly typed local variables (var – Contextual Keyword)

Implicitly typed local variables (var – Contextual Keyword)

Suppose I have created console application named ExplicitVars. Code given below all the variables are known as explicitly defined.

static void ExplicitVars()
{

// Explicitly typed local variables
// are declared as follows:
// dataType variableName = initialValue;

int ExplicitInt = 0;
bool ExplicitBool = true;
string ExplicitString = "go catch it...";
}

C# has introduced new token known as "var" which can decide the data type of the variable based on the value assigned to it. Above mention code can be written as.

static void ImplicitVars()
{

// implicitly typed local variables
// are declared as follows:
// var variableName = initialValue;

var ImplicitInt = 0;
var ImplicitBool = true;
var ImplicitString = " go catch it...";
}


When you see the types of each variable defined above it will be converted automatically by compiler based on the value assigned to it.

static void ImplicitVars()
{

// Implicitly typed local variables.
var ImplicitInt = 0;
var ImplicitBool = true;
var ImplicitString = "Time, marches on...";

// Print out the underlying type.
Console.WriteLine("myInt is a: {0}", ImplicitInt.GetType().Name);
Console.WriteLine("myBool is a: {0}", ImplicitBool.GetType().Name);
Console.WriteLine("myString is a: {0}", ImplicitString.GetType().Name);

}


Implicitly type conversion can be used also with arrays, generics and custom types.

static void ImplicitVars()
{

// More implicitly typed local variables.
var evenNumbers = new int[] { 2, 4, 6, 8 };
var myMinivans = new List();
var myCar = new SportsCar();

Console.WriteLine("evenNumbers is a: {0}", evenNumbers.GetType().Name);
Console.WriteLine("myMinivans is a: {0}", myMinivans.GetType().Name);
Console.WriteLine("myCar is a: {0}", myCar.GetType().Name);
}


You can also use the "var" inside for loops like below...

static void VarInForeachLoop()
{

var oddNumbers = new int[] { 1, 3, 5, 7 };

// Use "var" in a standard foreach loop.

foreach (var item in oddNumbers)
{
Console.WriteLine("Item value: {0}", item);
}

// Use a strongly typed System.Int32 to iterate over contents.
foreach (int item in oddNumbers) // it also works fine.
{
Console.WriteLine("Item value: {0}", item);
}
}

Limitations in Implicitly Typed Variables:

1) You can not use "var" as return values, parameter of method or field of any type. "Var” can be used inside method or roperty scope only.

class NeverCompile
{

// Error! var cannot be used as field data!
private var ImplicitInt = 100;

// Error! var cannot be used as a return value
// or parameter type!
public var ImplicitMethod(var p, var q){}
}

2) Variable defined using "var" must assigned initial value at the time of declaration and it should be null.

// Error! Must assign a value!
var ImplicitData;

// Error! Must assign value at exact time of declaration!
var ImplicitInt;
ImplicitInt= 0;

// Error! Can't assign null as initial value!
var refrenceType = null;

However it is possible to assign value null once it is recognized as reference type as below.

// OK, is fruit is a reference type!
var fruit = new Apple();
fruit = null;

However it is possible to assign value of implicit var to another varible either implicit or typed.

// Also OK!
var myInt = 0;
var anotherInt = myInt;
string myString = "Wake up!";
var myData = myString;

Following code also work fine.
static int ReturnVar()
{
var retVal = 999;
return retVal;

}

3) Nullable Implicit Type local is not possible.
var? notposible = null;//Error
var? i =0;//Error

Implicitly Typed variable is strogly typed variable.

Once value is assigned to the variable defined using var you can not change it's value which represents the different datatype. Means it is not same as used in VB using var or used in the scripting laguage like VBScript or javaScript. see the below code.

static void ImplicitTypingIsStrongTyping()
{

// The compiler knows "s" is a System.String.

var s = "This variable can only hold string data!";

s = "This works no error at all!...";

// Can invoke any member of the underlying type.
string upper = s.ToUpper();

// Error! Can't assign numerical data to a a string!
s = 44;

// Error! Can't perform this operation with string!
s = "Tejas" + 44;
}


When to User "var" ?

Generally if you know that variable will hold integer value then there is no need to declare it as var. you can declare it as int datatype but var token can be used with the LINQ query largely because output of the LINQ query can be vary on the based of the select statement when query so it is the best way to use var in the LINQ query.

Note: var is Contextual Keyword of C#. You can declare variable like int var =0 compiler will not give any error, but when it is used as var i=0 then complier treats "var" as contextual keyword.

What do you mean by Contextual Keyword?
A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. The following contextual keywords are introduced in this section:

get Defines an accessor method for a property or an indexer.
partial Defines partial classes, structs, and interfaces throughout the same compilation unit.
set Defines an accessor method for a property or an indexer.
where Adds constraints to a generic declaration.
yield Used in an iterator block to return a value to the enumerator object or to signal the end of iteration.
value Used to set accessors and to add or remove event handlers.

All query keywords introduced in C# 3.0 are also contextual. See Query Keywords (C# Reference).

See Also
Concepts

C# Reference
C# Programming Guide
C# Keywords

Saturday, May 17, 2008

Display your dll in Add Refrence Dialog of Visual Studio 2005

When you are adding any reference (adding assembly) to your project. you open the Add reference dialog it will show you below five tabs.

.Net Lists all .NET Framework components available for referencing.

COM Lists all COM components available for referencing.

Projects Lists Visual Studio projects in the current solution available for referencing. Select assemblies from this tab to create project-to-project references.

Browse Allows you browse additional files to find a component not listed in the current tab and add it to the list.

Recent Displays recently added references.

But if you want to see your assembly in the Add reference dialog under the .Net tab then what should you do?Will add it into GAC? Well! Well! Well just adding into GAC is not enough. Adding into the GAC it doesn't mean it will be visible in the Add Reference Dialog Under ".Net" tab.

What do you mean by adding DLL in to GAC (Global Assembly Cache)
"Adding DLL into GAC means it shared to all application running on same machine. But to add into GAC Assembly must be signed using SN.exe and you can add it using gacutil.exe"

There are three ways to display your assembly into Add Reference dialog.

•Way one: You have to copy your assembly and paste into the "Program Files\Microsoft Visual Studio .NET\Common7\IDE\Public Assemblies" (you can find these assemblies on the .NET tab) see below image.



•Way two: Set a reference path to the directory containing the assembly using the Reference Paths Page, Project Designer (C#).

Select your projects from solution explorer right click on it select property. Select reference property tab give folder path from where assembly resides. see below image.


•Way Three: Set a registry key that specifies the location of assemblies to display. You can either set the key under HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE if you add under HKEY_CURRENT_USER then it will be visible to that user only and if you add key under the HKEY_LOCAL_MACHINE then it will be visible to all users. (Don’t Forget to restart pc after setting this :) )

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework\\AssemblyFoldersEx\MyAssemblies]@="AssemblyLocation"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\\AssemblyFoldersEx\MyAssemblies]@="AssemblyLocation"

see below image.


I think way one and two are easy but three is little bit risk can cause harm to your computer.

Quiz for Readers:

Question 1: In default windows application System.Window.Forms.dll assembly is referenced by default when project is created of Window type but when you build the project the System.Window.Forms.dll will not be placed into bin folder why? And if I want to force to put into bin what should I do?

Question 2:
What is the difference between putting the dll files into “\Program Files\Microsoft Visual Studio 8\Common7\IDE\PublicAssemblies” and GAC?

Question 3: I have created project and added reference of the strong name assembly which is located at D:\MySignedAssemblies. Since it is strong name assembly it will be not copied into bin folder. Now time comes to run it to another computer.
What will be happened if another computer does not contain assembly which is referenced by my application?
What will be happened if another computer contains required assembly in GAC instead of bin?

Question 4: How CLR resolved the location of dll files? Can we override the default probing?

Question 5: Where is the physical path of GAC? What is the use of SN.exe and gacutil.exe?

Question 6: What do you mean by delayed signed?

Question 7:If you see the GAC Physical path in Windows Explorer you will be wondered that some dll files have same name then also in the same folder why it is so? (Hint: try to explore the physical path using cmd.exe or command.exe).

Friday, April 25, 2008

VirtualTechDays

Hi,
Guys
I have attended VirtualTechDays Events which is organized by Microsoft on 9th & 10th April which was about the three products
1)Windows Server 2008
2)Microsoft SQL Server 2008
3)Microsoft Visual Studio 2008.


It was amazing. There were 32 sessions. Each session is of 1:30 hrs.
You can download video and Power Point slides from here.


Wow!! I got the certificate too..... :) .

Thursday, March 20, 2008

Find Prime Number at Fastest Speed.

Introduction to the Prime Numbers:
A composite number is a positive integer which has a positive divisor other than one or itself. By definition, every integer greater than one is either a prime number or a composite number. The number one is considered to be neither prime nor composite.

For example,the integer 14 is a composite number because it can be factored as 2 × 7.

The first 15 composite numbers are
4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, and 25.

The firs 5 prime numbers are 2,3,5,7,11

Problem Description:I have find many programs which find the prime numbers or gives you whether the number is prime or not, or gives collection of numbers which are prime from the given number range but the problem in those programs are very slow and becomes Massey (and also sometimes hang your system)when you give the large number 100000 to find out prime number up to that number.

one of my colleague name mayur has suggested algorithm of find the prime numbers by the fastest way.The algorithm of Sieve of Eratosthenes pleast visit here.

C# code for that algorithm is given below.Try it and compare it with your program.

using System.Collections;

int range= 1000000;
BitArray numbers = new BitArray(range, true);

for(int i = 2; i < range; i++)
if(numbers[i])
{
for(int j = i * 2; j < range; j += i)
numbers[j] = false;
}

int primes = 0;

for(int i = 1; i < range; i++)
if(numbers[i])
{
primes++;
//Console.Out.WriteLine(i);
}

Console.Out.WriteLine();
Console.Out.WriteLine(primes + " out of " + range + " prime numbers found.");
Console.In.ReadLine();

The Older and simple program which was done in my school days.


ArrayList primeList = new ArrayList();

for(int i = 2; i < 100; i++)
{
bool divisible = false;

foreach(int number in primeList)
if(i % number == 0)
divisible = true;

if(divisible == false)
primeList.Add(i);
}

If you dare to beat above program then pleas visit this and send me your program after implementation best of luck guys.