Difference between var and dynamic  in C#?

Difference between var and dynamic in C#?

ALLCPL

3 года назад

133 Просмотров

Difference between var and dynamic in C#?

Var :
1) It is introduced in C# 3.0.
2) Statically typed – This means the type of variable declared is decided by the compiler at compile time.
3) Need to initialize at the time of declaration.
e.g., var str=”I am a string”;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string.
4) If the variable does not initialized it throw an error.
5) var myvalue = 10; // statement 1myvalue = “AllCPL”; // statement 2Here the compiler will throw an error because the compiler has already decided the type of the myvalue variable using statement 1 that is an integer type. When you try to assign a string to myvalue variable, then the compiler will give an error because it violates the safety rule type.

Dynamic:
1) It is introduced in C# 4.0
2) Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
3) Intellisense is not available since the type and its related methods and properties can be known at run time only
4) No need to initialize at the time of declaration.
e.g., dynamic str;
str=”I am a string”; //Works fine and compiles
str=2; //Works fine and compiles
5) If the variable does not initialized it will not throw an error.
6) dynamic myvalue = 10; // statement 1myvalue = “AllCpl”; // statement 2Here, the compiler will not throw an error though the type of the myvalue is an integer. When you assign a string to myvalue it recreates the type of the myvalue and accepts string without any error.


Sub-Description :
c# var vs dynamic,c# dynamic,c# interview questions and answers,dynamic,dynamic object,c# interview questions with answers,c# tutorials for beginners,programming,.net interview,.net interview questions,c# var,csharp interview questions,dot net interview questions,c# interview questions for experienced,interview,static type,visual studio,interview questions,training,c# interview question,tim corey,c# interview questions,c# training,.net

#var #dynamic #csharp

Тэги:

#C#_interview_Question #var_in_c# #dynamic_in_c# #var_keyword #dynamic_keyword #c#_interview_questions #var_keyword_c# #var_keyword_in_c# #dynamic_keyword_c# #var_and_dynamic_keyword_in_c# #c#_dynamic #dynamic #c#_interview_questions_with_answers #.net_interview #.net_interview_questions #dot_net_interview_questions #c#_interview_questions_for_experienced #interview #visual_studio #interview_questions #c#_interview_question #c#_training #.net #c#_interview_questions_and_answers
Ссылки и html тэги не поддерживаются


Комментарии: