Learning null-coalescing operator

I am pretty sure that most of the guys has never knew this operator and its also very rarely used. Since C# provides this and this is very useful and handy at certain times.

The short from of null-coalescing operator is ??.

It actually takes two operands.  So it returns the left hand operand if it is not null else returns right operand. So this is very useful while initializing any variable. let’s see a example

string name = null;
string otherName = "Brij";
string userName = name ?? otherName;
Console.WriteLine(userName);

As you can see, here is name is null then userName is assigned to otherName. and it will print Brij.

Continue reading

Exploring Nullable types : Part 2

This is second and last part of the post on Nullable type series. You can view the first part from here

Exploring Nullable types : Part 1

In this series, I will talking certain rules that we need to take care while using Nullable type. I will be taking scenario wise.

First scenario:

Int? a=8;
object o = a;
long d = (long)c;

It will be compiled successfully but will throw and Invalid Cast Exception. Means, you cannot cast it to any other type except the underlying type which is here int although  int type can be hold by long.

Continue reading

Generics and Constraints over Generics

In this post,  I am going to discuss about Generic Classes and bit more on this.  Just for a smooth start,

“Generics were introduced in .NET 2.0, which provides us a way to create Classes/Methods/Types and many more without specifing the specific type of parameters. Parameters must be provided at the time of creating the instances. So we can say Generics are only a blueprint/templated version and actual type is defined at Runtime.”

So lets first create a simple Class say Point Continue reading…

Some basics about C#

I have seen a lot of confusion amongst a lot developers about some basic things of C#. I am going to discuss some of them here.

The very first thing, In C# every thing is a struct or a Class. And every type(Class) is a derived from System.Object, whether is of reference type or Value type.

All Value type variables are derived from System.Value type and System.Value type itself is derived from System.Object. And every value type variables is declared sealed type so no one can derive from it.

Now Lets move some basic Questions.

– What is the difference string, String and System.String?

– What is the difference amongst int, System.Int32, System.Int64.

So these are few basic things, some always have confusion. So lets try to clear it out.

int c;

System.Int32 c;

int c=0;

System.Int32 c = 0;

int c= new int();

System.Int32 c = new System.Int32();

So what is the difference in all above. or Is there any differences?

In one word answer: NO

All of the above would be compiled and will produce the same and exact IL code.

It means all of these are same. Actually C# define primitive types and every primitive is directly mapped to some Class in FCL. So whenever you are going to write the primitive type, compiler while compiling finds the exact Class from the FCL and replaces with it.

Similarly, System.String or String or string all are same. Even I had confusion earlier between String and string. Even when you type both in Visual Studio IDE, both are in different color.

One more thing, I want to say every value type is initialized to its defined default value. Whether you give its default value or not Compiler does it for you, but this is not true for Reference Type.

One already know, writing int is mapped Int32 or is of 32 bit. But some people have different view, according to them int is of 32 bit in 32 bit machines and is of 64 bit on 64 bit machines. Which is absolutely wrong and int is always of 32 bit in C#, whether is of 32 bit or 64 bit machines.

Hope it clears…

Cheers,

Bri

IS vs AS operators : Performance Implications

If you are working as a C# programmer. You must know, the differences and performance implications of these operators IS vs AS. Some people who has not enough information about this, it’ll be helpful to them.

There are two operators IS as AS in C# and mostly used for same purposes. During our programming, we generally typecast the object into other type.

There are various scenarios, if you are typecasting , you may compile time error and other Run time error. Which obviously is not good for any application.

One thing, first I want to discuss, that as we know, System.Object is mother of all classes in C#. It means, whether you derive your class from System.Object specifically or not, CLR does this for you. So every object has always few basic method, that are inherited from System.Object. GetType also comes from System.Object. This always gives you the exact type of your object at run time. This method is non virtual so yo are not allowed to override this.

Now lets move to Is operator. For the safety of the code, whenever you are going to cast an object to other, say Class Student . you will be writing the code like

if( myobject is Student )
 { Student objStudent = (Student) myobject;
}

Obviously this is good code, because before typecasting to Student type, it is actually checking whether this is of Student type or not. Is Operator returns true if the object is of the same type else return false.

But what happens, if we write the code simply

 Student objStudent = (Student) myobject;

and where myobject is not of Student type, it’ll throw an exception. Actually at run time, CLR checks whether the object is of student type or not and it is not, so it throws an exception.

Now lets move to AS operator, this operator try to to typecast the object to a given type and if the typecasting is successful then it returns it as of object of that class else returns null.

Now we can write the above code as following,

 Student objStudent =  myobject as Student;
 if(objStudent !=null)
 {
 //use the object
 }

Here as we see in the first line, CLR first checks whether the object is of Student type then return object of that type else null. Actually type checking is not a simple task for CLR, it goes through all the hierarchy, i e base type and checks whether the object is of the current type or any base type.

So in the second one, CLR is checking this once while earlier one it is doing two time, first with IS operator and later in typecasting, which is obviously a overhead.

Here I also want to mention one thing, we should use AS operator judiciously, because it will never throw an exception while typecasting, so one always must have a check for null, before using this else it’ll through an exception.

On the other hand, if you are assign any value , say a input box or Label, one should use as operator. We can do in two ways, say we got one data row that came from database. Now,

textbox1.Text = data row["columnName"] as String;

because Text property can be assign any string or null, it will never barf. So this will work every time, but if you write

textbox1.Text = data row["columnName"].ToString();

It will be working fine till the value is not null else will through an exception because ToString() cannot be called over null value.

Hope you all have enjoyed this.

Happy coding!!

Brij

String.IsNullOrEmpty

Might be some of you already using this. But for others it could be a great utility method.

We use a method static method IsNullOrEmpty of string in most of our daily task/Projects a lot. It works fine in most of the cases, but it could work bizarre in some cases if not handled properly.

Say, you get a entry from UI, and having a check whether user has entered something or not. It would work fine as long as user enters the data or not.

But what happen if user enters just spaces. This method would return false, ironically this method is behaving as coded. But do we need this?

Obviously not, spaces could lead wrong entry in our database even can corrupt the data and leads to uncommon results/Y SODS/malfunctioning.

Although being a good developer, one always trim the input before having the check. But it also tends a lots of extra LOCs which we can save and can make our system less error prone.

As most of aware that the beauty of the extension methods that were introduced in c#3.0. So we can have a extension method over a string, which actually does the both first trimming and then checking for IsNullOrEmpty.

So we can have the extension method as

public static bool IsNullorEmpty(this String val)
 {
 if (val != null)
 {
 if (string.IsNullOrEmpty(val.Trim()))
 return true;
 else
 return false;
 }
 return true;
 }

Lets see both existing and our new method running.

My code is

static void Main(string[] args)
 {
 string name = "   ";
 Console.WriteLine(String.IsNullOrEmpty(name));
 Console.WriteLine(name.IsNullorEmpty());
 Console.ReadKey();
 }

The output is

Output

But if you are still using .NET 2.0, you can have a normal static method in your utility call, which does the job for as.

public static bool CheckNullorEmpty(string val)
 {
 if (val != null)
 {
 if (string.IsNullOrEmpty(val.Trim()))
 return true;
 else
 return false;
 }
 return true;
 }

Note: I must say, the limitation of existing IsNullorEmpty has been resolved in .NET 4.0. Means you don’t need to do all this. There is a new method String.IsNullOrWhiteSpace will do the both for you. But unlikely, most of us still working on .NET2.0/3.5

Hope you all must have liked it.

Looking in Func Delegates

This is an extension of my earlier blog post. I myself, find delegates as one of  the most powerful type to use in C#. It helps in writing very flexible and scalable program.

As I already discussed in my last blog that in the traditional way, we need to write more code.There I also discussed, One predefined delegate Action delegate that is provided by the framework.There are four flavors of Action delegate is provided.

One more type of predefined delegate that is provided by .NET that is counterpart Action delegate  . As we saw that it always returns void. But Func returns a value instead of void as Action does.

There is also 5 flavours of the Func delegate is provided.These are

– Public delegate TResult Func<TResult>()

— Public delegate TResult Func<TResult>()  // Take no parameter and returns a value

–  Public delegate TResult Func<T, TResult>(T t)  // Take one input parameter and returns a value

– Public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2)  // Take 2 input parameter and returns a value

– Public delegate TResult Func<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3)  // Take 3 input parameter and returns a value

– Public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 t1, T2 t2, T3 t3,T4 t4)  // Take 4 input parameter and returns a value

If we see the declaration, TResult is put at last, this is just a convention. One can put it wherever s/he wants.

First lets see first one , with no parameter and returning a value

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable and assigning it a function
Func<string> myFunc = SayHello;

//Calling function using Func Delegate
string returnedString = myFunc();

Console.WriteLine(returnedString);

Console.ReadKey();
}

private static string SayHello()
{
return "Hello Dude!!";
}
}

Now lets move to code to another overload of Func Delegate. It takes two input parameter and resturns a value.

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes two input parameters and returns a value) and assigning it a function
Func<double, double, double> myFunc1 = Add;

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5);

Console.WriteLine(sum);

Console.ReadKey();
}

private static double Add(double first, double second)
{
return first + second;
}
}

It is also same as Action delegate. i e It can also be used with Anonymous functions and Lambda functions. Lets have a quick look on both

Anonymous Function:

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes three input parameters and returns a value) and assigning it an Anonyomus function
Func<double, double, double, double> myFunc1 = delegate(double d1, double d2, double d3)
{
return d1 + d2 + d3;
};

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5, 5.5);

Console.WriteLine(sum);

Console.ReadKey();
}
}

Lambda Function:

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{

Func<Employee,string> checkEmployee = s=>{
if (s.Id > 11)
return s.Name;
else
return "Employee is not with the given Criteria.";
};

Console.WriteLine(checkEmployee(new Employee() {Id=12, Name="Brij"}));
Console.WriteLine(checkEmployee(new Employee() {Id=10, Name="Abhijit"}));

Console.ReadKey();
}
}

Hope you all must have enjoyed the delegates.

We use delegates a lot. But most of us, use the traditional way in programs. When I learnt first these Action and Func delegates few weeks back, I found it very useful. It helps us writing better and well organised code, also less error prone code. I talked to lot of developers, they didn’t have any idea about these predefined delegates. So I thought of sharing to you all.

Please share your valuable feedback.

Cheers,

Brij