C# - Dynamic Type or Typecast? - c#

Talking about performance, what is better in C#? Use Dynamic types or Typecast?
Like this (just an example, not the real implementation):
var list = new List<object>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = (Men)list[1];
men.SomeMenMethod();
Or this
var list = new List<dynamic>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = list[1];
men.SomeMenMethod();

The example is contrived as you know list[1] is a Men. So in that case either is identical.
Where dynamic becomes useful where you don't know the precise type, but you do know that at runtime that it will have a SomeMethod or property.
Of course if the type assumption is wrong, then the first throws an exception on the
var men = (Men)list[1]; line while the latter throws the exception on men.SomeMenMethod();

If possible, don't use either. Try to use type-safe solution that doesn't involve casting or dynamic.
If that's not possible, casting is better, because it's more clear, more type-safe (compiler can check that Men actually does have SomeMenMethod), the exception in case of an error is clearer and it won't work by accident (if you think you have Men, but you actually have Woman, which implements the same method, it works, but it's probably a bug).
You asked about performance. Nobody other than you can really know the performance of your specific case. If you really care about performance, always measure both ways.
But my expectation is that dynamic is going to be much slower, because it has to use something like a mini-compiler at runtime. It tries to cache the results after first run, but it still most likely won't be faster than a cast.

Related

Should I cast in my lambda or cast the IEnumerable?

In my project I have a MyClass which implements IMyClass. I need to return a list of IMyClass by transforming a list of other items. For simplicity's sake, assume that I can create a MyClass just by passing another item into its constructor, i.e. new MyClass(item).
Consider the following two lines, which (as far as I know) produce the same result:
var option1 = items.Select(item => new MyClass(item)).Cast<IMyClass>().ToList()
var option2 = items.Select(item => new MyClass(item) as IMyClass).ToList()
It seems to me that option #1 would require a double enumeration, once to cast all the items to my interface and once to generate the list. If I'm right then option #2 would be smarter. However, I've never seen any code using something like option #2, and I tend to assume that I'm not smart enough to come up with something clever that the rest of the C# community did not.
On a side note, I think option #2 is more aesthetically pleasing, but that's just me.
My question is: is my option #2 a better idea like I think it is? Are there are any gotchas I'm missing or other reasons why I'd want to stick with option #1? Or am I perhaps comparing two stupid ideas when there is a smarter third one that I'm missing completely?
I'd go for option 3:
var option3 = items.Select<Foo, IMyClass>(item => new MyClass(item))
.ToList()
Alternatively, don't use as but just cast normally:
var option4 = items.Select(item => (IMyClass) new MyClass(item))
.ToList()
Both of these seem cleaner than using Cast.
Oh, and as of C# 4 with .NET 4 (due to covariance), you could put a type argument on the ToList call instead:
var option5 = items.Select(item => new MyClass(item))
.ToList<IMyClass>()
It seems to me that option #1 would require a double enumeration
This is not true. In both cases, the items collection is only enumerated when you get to ToList().
The line
var option1 = items.Select(item => new MyClass(item)).Cast<IMyClass>().ToList()
is equivalent to
var option1 = items.Select(item => new MyClass(item)).Select(x => (IMyClass)x).ToList()
The only difference between the two is that the first one requires two function calls per item (unless C# inlines the lambdas somehow, which I don't believe is the case) while the second option requires only one.
Personally, I'd go with the second one as a matter of style.
Which one you use is a matter of preference, something we really cannot answer for you.
But your intuition if sort-of correct that Cast adds a second layer of iteration to your loop. It's very minor, and I doubt it will produce any measurable difference in performance, but the Cast method returns a new IEnumerable object that basically does this:
foreach (object obj in source) yield return (TResult)obj;
The effect is mostly another level on the call stack; since it uses yield it will only iterate on demand, like most other IEnumerable methods. But it will have to return though two levels of iterator state instead of one. Whether that matters for you is something you'll need to measure for your own applications.
(Also note that, at least according to the reference source, it does an unsafe cast, which might throw an exception if the cast is invalid. That's another reason to prefer your option #2.)
You can always provide explicit type arguments to your Select
var option2 = items.Select<IItem,IMyClass>(item => new MyClass(item)).ToList();
where IItem is a type or interface to which items could be cast.

Iterating through an object array; foreach(var... vs. foreach(object

object[] objArray = new object[]{"blah", 4, "whatever"};
foreach(var value in objArray) vs. foreach(object value in objArray)
I'm curious as to what the difference is between those, other than var must remain its type after assigned. Is one better than the other? Thanks.
From a purely functional perspective, var is just a shortcut for object here, since objArray's elements are of declared type object.
Using object is a sign to whoever's reading the code that the items in the array are not known to be any type more specific than object. The use of var does not connote this. In the minimal case you posted, it really doesn't make any difference to the clarity of the program which one you use.
If, on the other hand, it is not immediately clear from the context what type of object you are working with, then it may be advantageous to explicitly declare the type. On the other hand, if the type of the elements of the collection you're iterating over is verbose and obtrusive, then it may be advantageous to use var, so that the reader's eyes will be drawn to the logic of the code rather than a mess of generic parameters.
The only difference between var and any other type is that you let the compiler determine the type.
there is no difference between those two, var would be object in this case.
In your example no. But,
When declaring objects you get:
Boxing and Unboxing
However. When using var, it is compiled exactly as if you specified the exact type name.
So var tempval = 5; is the same as int tempval = 5;

What is the advantage of this type inference?

Using type inference we can write:
var myList = new List<int>();
but it's not really helping is it? Because the still requires us to only add ints, so wouldnt it have been easier to just declare the variable of 'int' instead of 'var' ?
The var doesn't change the output of the compiler - it only makes the code shorter.
The only time that var offers anything else is in regards to anonymous types:
var foo = new { Bar = 123 };
It is important to understand that var doesn't mean dynamic or variable (in the sense that it allows the type of the object to vary) - it just allows you to declare a variable and have the compiler infer the type as if you had declared it.
IEnumerable<MadeUpEmbarrassinglyLongClassName> stupidVariable = new IEnumerable<MadeUpEmbarrassinglyLongClassName>();
vs
var stupidVariable = new IEnumerable<MadeUpEmbarrassinglyLongClassName>();
Which is easier to read?
Its more concise than:
List<int> myList = new List<int>();
I guess this might be easier to read that using var though, although in this trivial case there's not much in it.
In addition, if the variable is named sensibly, then the what type it is should be fairly clear anyway.
The var is of unknown type until it is assigned a value. As soon as you assign a value, it becomes the typeof to which it is assigned. This var is used in situation when you can't infer at compile time as to what value will be passed to it. The other situation where var comes in handy is in LINQ queries. Rather than creating a special class to handle your query returns, you simple assign the result to var and it does the rest. You will surely compliment var once you start using LINQ
In your example, there is no advantage. In fact, I believe that code readability suffers a bit (opinion).
The answer to this quesiton boils down to personal preference. The compiler will infer List<int>() if var is used. Which would you prefer to look at? Which would your peers prefer to look at?

var keyword in C# 3.0 [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What’s the point of the var keyword?
Hello everyone,
I want to confirm whether my understanding is correct. If I do not use LINQ, then the only benefit of using var is to make brevity? Is that correct understanding?
No, you can use var to construct anonymous types, regardless of whether or not you're using LINQ:
var anon = new { Name = "Anonymous", Age = 42 };
It's also easier for working with types like this. When you have very long generic types, the type name can get in the way of visually identifying the variable name as part of a declaration.
Dictionary<string, Dictionary<int, ICollection<object>>>
especially if you go back through and change it to
Dictionary<string, IDictionary<int, ICollection<object>>>
From msdn:
Beginning in Visual C# 3.0, variables
that are declared at method scope can
have an implicit type var. An
implicitly typed local variable is
strongly typed just as if you had
declared the type yourself, but the
compiler determines the type. The
following two declarations of i are
functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
MSDN Link Here
If you're not using LINQ, var allows you to only declare the type of the variable once, instead of twice.
Example
var myObject = new MyObject();
vs
MyObject myObject = new MyObject();
This can only be done locally, and is also useful for declaring anonymous types.
Example
var myAnon = new { Name = "Something", Count = 45 };
Other than for LINQ queries I would be very cautious in using the var keyword. There are specific instance when you just need an anonymous type but this is few and far between I think. Var can lead to very confusing code as you have no idea what the type you are dealing with when reading the code unless you use the intellisense crutch.
It worries me more and more that I see so many snippets and bits of code that do the following... it's lazy and not what the var keyword was intended for:
// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();
// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();
So use it for LINQ... use it for anonymous types (if you do use anonymous types outside of LINQ you should really scrutinize why you need to).
Quote from MSDN (very last line of article) regarding use of var:
However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.
Don't use it as a short cut to save keystrokes, the next guy looking at your code will appreciate it.
Pretty much, yes. var may be used wherever the compiler can infer the type of the variable from whatever value you are assigning to it. (The type inference rules are quite complex however, so you may want to read the C# specification for a full understandin.)
It's not quite correct in that the var keyword is required for defining anonymous types. For example:
var foo = new { abc = 1, def = 2 };
which can be used outside of LINQ queries as well as inside, of course.
I don't think using var should be a problem - and I prefer it for exactly the reasons of code readability. First of all, var is only syntactic sugar and just gets compiled away to a proper type when IL is emitted. And as far as the code readability goes, it makes more sense to focus on the purpose the variable is used for, and how it is assigned than just its type. VS .NET editor shows the type in the line following it anyway - if you just hover on it. So this shouldn't be a problem at all. And as far as the debugging goes - if you see Autos/Local/Watch windows - they display the types of all the members.
It makes more sense for me to see code like this:
var customers = GetCustomerList();
foreach (var customer in customers)
{
customer.ProcessOrders();
}
as opposed to
List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
customer.ProcessOrders();
}
var is in its fairness limited to using in local variable declarations which are also initialized at the time of declaration. And in that one case, if you omit the actual type it definitely improves readability IMO.
EDIT: And it would unfair on my part not to warn against the usages as below:
var x = 20;
This is not good; when the literal is applicable to multiple types, you need to know the default type of the literal and hence understand what is infered for the type of x. Yes, by all means, I would avoid such declarations.
I believe it is also used in the WCF (Windows communication Foundation) when dealing with data obtained via webservices and the like.
I've also found that the use of var also eases refactoring in low-coupled designs. This is because we tend to strong type variables, but normally the code that follows is expecting weaker types. Using var you'll offset type changes to the compiler.

What is the "< >" syntax within C#

I have been learning about the basics of C# but haven't come across a good explanation of what this is:
var l = new List<string>();
I don't know what the <string> is doing or if it's the List that is doing the magic. I have also seen objects been thrown within the < > tags.
Can someone explain this to me with examples, please?
That is the generic syntax for C#.
The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.
For example, the old way:
ArrayList foos = new Arraylist();
foos.Add("Test");
worked by making ArrayList store a list of System.Objects (The base type for all things .NET).
So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:
foos.Add("Test" as System.Object);
string s = foos[1] as String.
This causes a performance penalty from the casting, and its also unsafe because I can do this:
ArrayList listOfStrings = new ArrayList();
listOfStrings.Add(1);
listOfStrings.Add("Test");
This will compile just fine, even though I put an integer in listOfStrings.
Generics changed all of this, now using Generics I can declare what Type my collection expects:
List<int> listOfIntegers = new List<int>();
List<String> listOfStrings = new List<String>();
listOfIntegers.add(1);
// Compile time error.
listOfIntegers.add("test");
This provides compile-time type safety, as well as avoids expensive casting operations.
The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class.
public class Adder<T>
{
public T AddTwoThings(T t1, T t2)
{
return t1 + t2;
}
}
Adder<String> stringAdder = new Adder<String>();
Console.Writeline(stringAdder.AddTwoThings("Test,"123"));
Adder<int> intAdder = new Adder<int>();
Console.Writeline(intAdder.AddTwoThings(2,2));
For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.
It's generics - it's a form of type parameterisation. In your example, it's making l refer to a list of strings - the list will only ever contain strings: the compiler treats it (pretty much) as if everywhere that the API docs mention "T" it actually says "string". So, you can only add strings to it, and if you use the indexer you don't need to cast to string, etc.
To be honest, giving generics detailed coverage on an online forum is pretty much impossible. (In C# in Depth, I take nearly 50 pages talking about generics.) However, armed with the name of the feature, you should be in a much better position to find out more. The MSDN "Introduction to C# Generics" is probably a good starting point.
Asking specific questions about generics on SO is likely to yield good results - I just don't think it can really be covered properly in one question/answer.
This is .NET Generics. The type within the < > denotes the type of element contained in the list.
with ArrayList you'd have to cast the elements inside...
int x = (int)myArrayList[4];
with List you can avoid that step because the compiler already knows the type.
int x = myList[4];
Generics are available in .NET 2.0 and later.
Those are generics. You are making a List that only contains strings. You could also say
List<int>
and get a list that only contains ints.
Generics is a huge topic, too big for a single answer here.
Those are known as Generics (specifically List is a generic class).
Reading from MSDN
Generics (C# Programming Guide)
An Introduction to C# Generics
Generics in the .NET Framework
This is generics in action. A regular List stores items of type Object. This requires casting between types. This also will allow you to store any kind of item in one instance of a list. When you are iterating through items in that list you cannot be sure that they are all of a certain type (at least not without casting each item). For instance lets say you create a list like this:
List listOfStrings = new List();
Nothing prevents someone from doing something like this:
listOfStrings.add(6); //Not a string
A generic list would allow you to specify a strongly-typed list.
List<string> listOfStrings = new List<string>();
listOfStrings.add("my name"); //OK
listofStrings.add(6); //Throws a compiler error
There is a more thorough examples on here Generics
< > is for generics. In your specific example, it means that the List is a List of strings, not say a list of ints.
Generics are used to allow a type to be, well, generic. It's used ALOT in Collections to allow them to take different types so that they can function much like a normal array and still catch invalid types being assigned at compile time. Basically it allows a class to say "I need to be associated with some specific type T, but I don't want to hard code exactly what that type is, and let the user select it.". A simple array for instance might look something like:
public class MyArray<T> {
private T[] _list;
public MyArray() : this.MyArray(10);
public MyArray(int capacity)
{ _list = new T[capacity]; }
T this[int index] {
get { return _list[index]; }
set { _list[index] = value; }
}
}
Here, we have a private list of type T that is accessed by using our class like a normal array. We don't care what type it is, it doesn't matter to our code. But anyone using the class could use it as, say MyArray<string> to create a list of strings, while someone else might use it as MyArray<bool> and create a list of flags.

Categories

Resources