Introduction to object
The object class is the base class for all ohter classes; in other words all derived types are inherited from the object base type. We can assign values of any type to the object type variable (when the value type is converted to an object it is called "boxing" and when the variable type object is converted into any other value type is called "unboxing").
Example:
- object a = 10;
- object b = "This is test string";
- object c = a;
-
-
- object k = "jignesh";
- k = 10;
Introduction to var keyword
The var keyword was introduced in C# 3.0. It is an implicit type and the type is determined by the C# compiler. There is no performance penalty when using var. The C# compiler assigns types to the variable when it assigns the value.
Example:
- var a = 10;
- var b = "This is test string";
- var c = b;
-
- var words = new string[] { "apple", " banana", "peach", " grape" };
It makes programs shorter and easier to read. In short the var keyword is an implicit way of defining data types. It is an indirect way of defining the variable type. The “var” keyword defines the data type statically (at compile time) and not at runtime.
The var keyword is very useful when:
- We have a long class name so that our code is not so readable. var makes it short and sweet.
- We use LINQ and anonymous types that help us reduce the code (reduce effort to create a new class).
Introduction to Dynamic Keyword
C# 4.0 introduced a new type called "Dynamic". Dynamic is a new static type that is not known until runtime. At compile time, an element with dynamic is assumed to support any operation so that we need not be worried about the object, whether it get the value from COM, the DOM, from reflection or anything else in the program. Errors are caught at runtime only. The dynamic type in C# uses the Dynamic Language Runtime (DLR) introduced as a new API in the .Net Framework 4.0. Type dynamic behaves like an object in most cases, but the expression of type dynamic is not checked by the compiler. The type's dynamic status is compiled into a variable type object that is dynamic at compile time, not at run time.
At compilation a dynamic is converted into a System.object and the compiler will emit the code for type safety during runtime. It suffers from boxing and unboxing because it is treated as a System.Object and also the application's performance will suffer siince the compiler emits the code for all the type safety.
Example:
- dynamic i = 10;
- dynamic s = "Jignesh Trivedi";
-
- string p = "This is test";
- dynamic k = p;
-
- dynamic other = 10;
-
- other = "Jignesh";
We can define a dynamic variable, property, field and parameter, return value, type constraint and so on.
-
- static dynamic field;
-
-
- dynamic name { get; set; }
-
-
- public dynamic Method(dynamic parameter)
- {
- dynamic local = "return string";
- int other = 0;
-
- if (parameter is string)
- {
- return local;
- }
- else
- {
- return other;
- }
- }