Var vs. Object data type in C#

Knowing which data type to use in different situations is generally a basic level decision. I mean you do not need to think very hard about storing regular numbers or storing words. I hope you don’t believe that. Actually, choosing the correct data type to store your data can have serious implication on memory, storage, precision and access. So spend some time learning and studying the different data types and try to imagine which situations you would use a string for or perhaps a float.

This article will cover 2 data types. First we will discuss the var data type. The var is a nice one because you do not need to decide whether to use a System.String or System.Int32 because when you associate a value to the var, the compiler will determine the type for you. NOTE: using var does not remove the responsibility from understanding the memory usage, storage usage, precision, etc..of the data type. It’s just makes things a bit easier and faster, but use it with caution.

image

You see above that I set str to a string, intg to an integer and dec to a decimal value and the compiler determined which data type to convert var to. With var you will get access to the the data type class properties and members as you see from the drop downs. The same is not true for an object. It is not known at compile time what data type the value stored within the object is. You can store classes or generic lists in an object. I.e. both reference and value types can be stored in an object.

image

Similar situation if you have a simple class named Person:

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
public class Person
{
    public string Name { get; set; }
    public string Age { get; set; }
}
[/sourcecode]

image

If I use var to contain the class, then the properties within the class are available, however if I use object they are not.

When to use an object in C#? I use object variables in situations when I will receive a list of data but a m not certain of the data types within them. For example:

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
List<object> fields = new List<object>(BuildFieldList(Query));
[/sourcecode]

The Query identified above is a string of columns a user has selected from a reporting tool. I am not certain which column or how many the user has selected. Therefore I decided to use an object variable.

When to use a var in C#? Following along the same line as the above example, I would use a var to contain the result set from the Query that was executed.




Leave a Comment

Your email address will not be published.