What is the difference between var and dynamic c#? [duplicate] - c#

This question already has answers here:
What's the difference between dynamic (C# 4) and var?
(14 answers)
Closed 7 years ago.
I'm not sure what is the exact different between both declarations.
When should I use var and when should I use dynamic.
Thanks a lot!
Don

var is type of variable decided by the compiler at compile time. Need to initialize at the time of declaration. All errors are caught on compile time.
dynamic is type of variable decided by the compiler at runtime time. No need to initialize at the time of declaration. All errors are caught at runtime.
dynamic variables can be used to create properties and return values from a function. var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.

Related

Is there a way to shorten field declaration in C#? [duplicate]

This question already has answers here:
Is there a way to abbreviate a custom class type declaration?
(4 answers)
Implicit typing; why just local variables?
(6 answers)
Closed 2 years ago.
Why do I have to write:
public VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName> field = new VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>();
Instead of:
public var field = new VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>();
Is there any way to shorten this ridiculous declaration?
Why do I have to write two identical types in a single line?
Upd.
I have found that using "dynamic" keyword instead of "var" perfectly solves this problem!
Please feel free to provide any info on the perfomance (or other) issues with this solution!
You can use a type alias. Documentation can be found here. Link to alias for generic class: here
using YourShortName = VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>;
Usage
public YourShortName field = new YourShortName();
See here for why you can only use var for local variables.
And see here for an in depth look at dynamic and why it's not even remotely close to using var.

How can I cast an object using a known Type object? [duplicate]

This question already has answers here:
Casting a variable using a Type variable
(11 answers)
Closed 4 years ago.
I have a Type variable and I need to cast another object to it. (one which I know what the type is, but currently its an "object" type). I need to do this for reasons that aren't really important to the answer.
// Pseudocode
MyObjectClass myTypedVar = new MyObjectClass();
Type myKnownType = myTypedVar.GetType();
var anotherObject = (myKnownType) anObjectVarThatIsReallyMyObjectClass;
I've read this page Type Casting an Object using a "Type" Object in C# and I understand but I don't think it applies directly. I anticipate a solution using reflection, but I just haven't been able to figure it out myself.
If I understand you correctly, you could use the Convert.ChangeType method:
var anotherObject = Convert.ChangeType(anObjectVarThatIsReallyMyObjectClass, myKnownType);
You won't get any kind of compile-time checking when using a dynamic type like this though. Please refer to the following blog post for more information about this.
Generic type parameters and dynamic types in C#: https://blog.magnusmontin.net/2014/10/31/generic-type-parameters-and-dynamic-types-in-csharp/

Register a type at runtime using Unity Container [duplicate]

This question already has answers here:
Setting generic type at runtime
(6 answers)
Closed 5 years ago.
Why can I not do this? Where obj value is a valid type.
Type type = obj.Value.GetType();
this.unityContainer.RegisterType<type>();
OR
this.unityContainer.RegisterType(obj.Value);
When I can do this... where obj value would be the same type but known at compile time.
this.unityContainer.RegisterType<object, actualType>("Name");
The end goal of mine is to be able to register several different types at run time.
Anything in angle brackets must be known at compile time - generics are a compile-time feature. There are plenty of overloads of RegisterType that take a runtime-determined Type object such as you are doing here.
Move your runtime type reference out of the angle brackets and into the parentheses.
this.unityContainer.RegisterType(obj.Value.GetType());

Extension functions does not work for dynamic objects [duplicate]

This question already has answers here:
Extension method and dynamic object
(3 answers)
Closed 6 years ago.
I have a Extension Function named ParseLong for string.
public static long ParseLong(this string x, long Default = 0)
{
if (!string.IsNullOrEmpty(x))
long.TryParse(x, out Default);
return Default;
}
And works fine:
long x = "9".ParseLong();
However for dynamic objects like:
dynamic x = GetValues();
x.StartValue.ToString().ParseLong();
generates the error:
'string' does not contain a definition for 'ParseLong'
Correct, extension functions do not work for dynamic objects. That is because the dynamic object, when being told to execute ParseLong, has no clue what using directives were in your C# code, so cannot guess what you want to do.
Extension methods are 100% a compiler feature (only); dynamic is primarily a runtime feature (although the compiler has to help it in places).
You could just cast, though, if you know the type:
long x = ((string)x.StartValue).ParseLong();
(which swaps back from dynamic to regular C#, so extension methods work)

Where are the array types? [duplicate]

This question already has answers here:
What's the magic of arrays in C#
(8 answers)
Closed 9 years ago.
It's not a problem to use MakeArrayType() if we want to make a array type of a specific type, for example, the char array:
typeof(char).MakeArrayType()
Of course it's more intuitive to use typeof(char[]) instead.
And the property Assembly of a type tells us what the assembly where the type is.
So the following code should be a reasonable example to find a type in an assembly:
var chars=new[] { '\x20' };
var typeofCharArray=chars.GetType();
var assembly=typeofCharArray.Assembly;
var doesContain=assembly.GetTypes().Contains(typeofCharArray);
But doesContain says it DOESN'T, it's false. This happens regardless the array type is from MakeArrayType() or typeof(), or an instance's GetType.
There's a doubt that it was forwarded to other assemblies that I've read from Assembly.GetTypes. And I tried:
var assemblyContainsTypeOfCharArray=(
from it in AppDomain.CurrentDomain.GetAssemblies()
let types=it.GetTypes()
where types.Contains(typeof(char[]))
select it).FirstOrDefault();
The interesting thing is assemblyContainsTypeOfCharArray is null.
Where are the array types?
Simply: GetTypes() returns the types that are actually declared in that assembly. The array types are... not. They claim to be from there, but that is just returning the element-type's Assembly information. The array type isn't actually declared in there (it isn't actually declared anywhere - it is an invention of the JIT, on-the-fly).
So basically: the array type lies. Shame on it.

Categories

Resources