I am new to .NET C# and I was reading the code below:
var model = new TenantPageViewData<Tenant>(contentModel)
I can't understand <MyClass>, What does it mean to put <> in the code.
Also if you can guide me to documentation regarding this it will be great.
That is the syntax for specifying the type parameter for an open generic type. You can read more about generics here:
http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
If you are new to C#, it will seem complicated at first, but a lot of the language makes use of this feature so it will be time very well spent learning it.
With the general documentation and answer out of the way, in this specific case, the TenantPageViewData exposes a generic parameter. You read that as "a TenantPageViewData<> of Tenant".
The signature for that class will look something like:
public class TenantPageViewData<T>
{
}
Where T is simply a placeholder you can reference in code that will, at compile-time, become strongly-typed to the type of argument you specify.
This class definition can be referred to as an "open" generic type because the placeholder T is, as yet, unrealised. The declaration var something = new TenantPageViewData<Tenant>() is a "closed" generic type because the generic argument is known to now be Tenant in this instance.
Type identity is per closed generic type, so a TenantPageViewData<Tenant> is not a TenantPageViewData<Landlord>, and static members of a generic class honour this also (which is a common pitfall of learning generics).
Other examples include List<string> usually read as "a List<> of string", and the comical Cup<T> :-)
these type of brackets I believe are used for marking generics.
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
In C#, the angle brackets (< and >) are most often used to enclose a parameter of a generic class. For example, the .Net framework provides a List class where 'T' denotes the type of objects that will be contained in the list. Therefore, when the list is created as
List<string> myList = new List<string>();
you are creating a usable, type-safe instance of the List class.
Some good info on it here.
Related
I ran into a problem while doing my job, which is porting software from flash AS3 to .NET/Mono. In AS3 code base I can find many Object declarations that are initialized like this:
private const MAPPING:Object =
{
ssdungf:'flydung',
ssdungt:'flydung',
superfutter:'superfeed'
}
The best option for me would be in C# using anonymous type like this:
var MAPPING = new
{
ssdungf = "flydung",
ssdungt = "flydung",
superfutter = "superfeed"
};
The problem is... well let me quote MSDN (source):
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type
But they don't say why.
So the question remains: why you cannot declare a field and property as having an anonymous type? Why .NET creators stripped it from that option?
I am getting warning here from SO that my question appears subjective, but I think it is not at all - there need to be objective reason for that.
As for me, I don't see any obstacles for that but somehow it is not supported. As compiler can easily generate the type for field or property of class, in a same manner as it does for local variables.
The option for me was to use dynamic type but unfortunately Mono engine I am using is stripped from that.
Also the option for me is to use object type and using later reflection to find these fields:
private static readonly object MAPPING = new
{
ssdungf = "flydung",
ssdungt = "flydung",
superfutter = "superfeed"
};
But using reflection is this situation is dirty I would say.
I tried to find answer, but I really didn't find any. Here are some SO answers to similar questions, but they don't answer why:
Can a class property/field be of anonymous type in C# 4.0?
Declaring a LIST variable of an anonymous type in C#
How do you declare a Func with an anonymous return type?
Why you cannot declare a field and property as having an anonymous type?
Because C# is statically typed, so any memory location has to be given a type, and declaration does so. With locals we can infer from context if its initialised at the same time as declaration with var but that is a shorthand for a type that is usable even when the type hasn't got a name.
What would a field with an anonymous type, that is to say a statically-bound but indescribable type, mean?
dynamic would indeed be the closest analogy to the code you are porting, but since that isn't available to you, you might consider using an IDictionary<string, object> (which incidentally is how ExpandoObject, which is often used with dynamic to have objects that behave more like javascrpt objects, works behind the scenes). This would be slower and less type-safe than if you created a class for the object needed, but can work.
The problem on an anoynmous property is: how do you get/set it?
Suppose it would work:
class MyClass
{
public MyField = new { TheValue = "Hello World" };
}
Now in your consuming code you´d write code to read the code:
MyClass m = new MyClass();
m.MyField.TheValue = "newValue";
How was this different from having a type for MyField? All you´d get is that you can omit two or three lines of code whilst gaining nothing. But I think you might produce many problems as no-one knows what he can assign to/expect from that member.
Furthermore you can´t do much with an anonymous object, basically you can just set it and read it. There are no methods (except Equalsand GetHashCode inherited from object) that you can call so the opportunities are quite low.
Last but not least an anonymous object is usually used as temporaryily, for example within a Select-statement. When you use it you say: this type is going to be used only within the current specific scope and can be ignored by the entire world as internal implementation-detail. Creating a property of an anonymous type will expose such a detail to the outside. Of course you could argue that the designers could at least allow them for private members, but I guess doing so would bypass the complete concept of accessability for nothing.
I was reading the Covariance and Contravariance in C#.
According to my understanding,
If we have a class Animal and a derived class Cat then,
Covariance feature makes the compiler accepts passing a Cat type object to Animal type object and Contravariant is vice-versa.
Everything is ok till I read this line.
"To annotate type-covariance you use out parameter and for contravariant you use in parameter"
According to me, a parameter decorated with out keyword => the value must be assigned to that particular parameter in a function.
I have difficulties to associate the out keyword to covariance and in keyword to contravariant.
How are these two related ? Any super simple examples for both?
Thanks in advance.
Both covariance and contravariance in C# 4.0 refer to the ability of using a derived class instead of base class. The in/out keywords are compiler hints to indicate whether or not the type parameters will be used for input and output.
Covariance
Covariance in C# 4.0 is aided by out keyword and it means that a generic type using a derived class of the out type parameter is OK. Hence
IEnumerable<Fruit> fruit = new List<Apple>();
Since Apple is a Fruit, List can be safely used as IEnumerable
Contravariance
Contravariance is the in keyword and it denotes input types, usually in delegates. The principle is the same, it means that the delegate can accept more derived class.
public delegate void Func<in T>(T param);
This means that if we have a Func, it can be converted to Func.
Func<Fruit> fruitFunc = (fruit)=>{};
Func<Apple> appleFunc = fruitFunc;
Why are they called co/contravariance if they are basically the same thing?
Because even though the principle is the same, safe casting from derived to base, when used on the input types, we can safely cast a less derived type (Func) to a more derived type (Func), which makes sense, since any function that takes Fruit, can also take Apple.
out is a contextual keyword, i.e. depending on its placement, it means different things.
You are talking about the parameter modifier. But that's not what it is with regards to Co- and Contravariance. When the keyword is used in a generic interface definition, it is the generic modifier, which is something else completely.
out keyword serves different purposes. As you noted in the context of "generic type parameters" it acts as a keyword to make "covariance" work, another use is similar to ref keyword which we use to get multiple return values from a Method.
If you look at the documentation for out-keyword in MSDN two purposes of out keyword will be listed. Not to be confused it acts different based on the context.
You can find similarities with new keyoword also, it also serves different purposes. AFAIK they are
To create new instance of a class. object obj = new object();
To explicitly shadow base class method or property. protected new void BaseMethod(){}
Generic parameter constraint. private void MyGenericMethod<T>(T t) where T:new()
I think Microsoft guys make this feature very complexe by using not clear names for the feature name and not good keywords for the feature parameters.
I know this name from Covariance and contravariance of vectors (Mathe) and when I hear about it first time in C# I got a shock!
#JoesphAlbahari in his book C# 4 In a Nutshell have explained this topic very well page 109-112. I recommend you really to read it.
In C#, I would like to figure out if it's possible to declare an anonymous type where the fields are not known until run-time.
For example, if I have a List of key/value pairs, can I declare an anonymous type based on the contents of that list? The specific case I'm working with is passing parameters to Dapper, where I don't know ahead of time how many parameters I will have.
List<Tuple<string, string>> paramList = new List<Tuple<string, string>>() {
new Tuple<string, string>("key1", "value1"),
new Tuple<string, string>("key2", "value2")
...
};
I'd like to convert this List (or an equivalent Map) into an anonymous type that I can pass to Dapper as query parameters. So ideally, the above list would wind up looking like this, if defined as an anonymous type:
new { key1=value1, key2=value2, ... }
I've seen several questions on StackOverflow asking about extending anonymous types after they are declared ("extendo objects"), or declaring arbitrary fields on an object after it's created, but I don't need to do that... I just need to declare the types dynamically up-front once. My suspicion is that it will require some fancy reflection, if it's possible at all.
My understanding is that the compiler defines a type for anonymous classes under the hood at compile-time, so if the fields of that class are not available until run-time, I might be out of luck. My use case may in fact be no different in actuality than using an "extendo object" to define arbitrary fields, whenever.
Alternatively, if anyone knows of a better way to pass query parameters to Dapper (rather than declaring an anonymous class), I would love to hear about that as well.
Thanks!
UPDATE
Sorry for the delay in getting back to this one! These answers were all great, I wish I could give points to everyone. I ended up using jbtule's solution (with edit by Sam Saffron), passing IDynamicParameters to Dapper, so I felt I had to give the answer to him. The other answers were also good, and answered specific questions that I had asked. I really appreciate everyone's time on this!
Dapper's creators were very aware of this problem. This kind of functionality is really needed for INSERT and UPDATE helpers.
The Query, Execute and QueryMultiple methods take in a dynamic parameter. This can either be an anonymous type, a concrete type or an object that implements IDynamicParameters.
public interface IDynamicParameters
{
void AddParameters(IDbCommand command, Identity identity);
}
This interface is very handy, AddParameters is called just before running any SQL. Not only does this give you rich control over the parameters sent to SQL. It allows you to hook up DB specific DbParameters, since you have access to the command (you can cast it to the db specific one). This allows for support of Table Values Parameters and so on.
Dapper contains an implementation of this interface that can be used for your purposes called DynamicParameters. This allows you to both concatenated anonymous parameter bags and add specific values.
You can use the method AddDynamicParams to append an anonymous type.
var p = new DynamicParameters();
p.AddDynamicParams(new{a = "1"});
p.AddDynamicParams(new{b = "2", c = "3"});
p.Add("d", "4")
var r = cnn.Query("select #a a, #b b, #c c, #d d", p);
// r.a == 1, r.b == 2, r.c == 3, r.d == 4
In C#, I would like to figure out if it's possible to declare an anonymous type where the fields are not known until run-time.
Anonymous types are generated by the compiler. You want to know if the compiler will generate you a compiler-generated type with field types not known to the compiler. Clearly it cannot do so; as you correctly surmise, you are out of luck.
I've seen several questions on StackOverflow asking about extending anonymous types after they are declared ("extendo objects")
We usually call those "expando" objects.
If what you want to do is make an expando object based on a dictionary of key-value pairs, then use the ExpandoObject class to do that. See this MSDN article for details:
http://msdn.microsoft.com/en-us/magazine/ff796227.aspx
If what you want to do is generate a bona-fide .NET class at runtime, you can do that too. As you correctly note, you need some fancy reflection to do so. What you want to do is make a collectible assembly (so-called because unlike a normal assembly, you generate it at runtime and the garbage collector will clean it up when you are done with it.)
See http://msdn.microsoft.com/en-us/library/dd554932.aspx for details on how to make a collectible assembly and emit a type into it using a TypeBuilder.
You can't use an anonymous type. Anonymous types are generated by the compiler rather than at run-time. You could certainly use dynamic though:
dynamic dynamicObj = new ExpandoObject();
var objAsDict = (IDictionary<String, Object>)dynamicObj;
foreach(var item in paramList)
{
objAsDict.Add(item.Item1, item.Item2);
}
You can then use dynamicObj as a regular object:
Console.WriteLine(dynamicObj.key1); // would output "value1"
foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
{
dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
}
I am working on creating a excel file from within .NET, using this Excel Library
I am getting the warning mentioned in the title. Any ideas?
Just for future reference, and understanding, the error message:
The non-generic type '' cannot be used with type arguments
is replaced with some class, indicates that within your code you are attempting to make use of a non-generic class in a generic way. More specifically you are using some syntax which is incompatible with that type, in this case the <> generic braces on the type "Pair".
To typically solve the problem
Identify the types use within the file, specifically its use in a generic way. (This should find them: Ctrl + F > "SomeClass<")
Ensure that the type is as expected (F12 on the type should take you to its declaration)
If the type is different to the expected type you should make use of a using alias to point to the correct type namespace i.e.
using Pair = Fully.Qualified.Namespace.Of.Pair;
If the type is as expected ensure that it is generic, if not you can either modify it to be generic, if you have permission/access to do so, or you could select/create a different type which is more suitable for your purpose.
Alternativly you could modify your use of the type to be non-generic
It means that Pair in the code above is referring to System.Web.UI.Pair instead of some other "pair" class such as System.Collections.Generic.KeyValuePair (which is generic).
Depending on which Pair the above code was meant to instantiate, use something like
using Pair = MyNamespace.Pair;
to resolve the issue (this example assumes you really want to use MyNamespace.Pair).
Update:
It seems that in your case the exact solution is
using Pair = QiHe.CodeLib.Pair;
Because MSDN provides the Pair definition as:
[SerializableAttribute]
public sealed class Pair
There is not a definition that includes Pair<T1, T2>. If there is another Pair class, you need to include that namespace in your 'using' clause.
What is the design decision to lean towards not returning an anonymous types from a method?
You can return an instance of an anonymous type from a method - but because you can't name it, you can't declare exactly what the method will return, so you'd have to declare that it returns just object. That means the caller won't have statically typed access to the properties etc - although they could still pass the instance around, access it via reflection (or dynamic typing in C# 4).
Personally I would quite like a future version of C# to allow you to write a very brief class declaration which generates the same code (immutable properties, constructor, Equals/GetHashcode/ToString) with a name...
There is one grotty hack to go round it, called casting by example. I wouldn't recommend it though.
Because an anonymous type has no name. Therefore you cannot declare a return type for a method.
Because C# is statically typed language and in a statically typed language the return type of a method needs to be known at compile time and anonymous types have no names.
How can you use your type inside your method if the definition is only in the call of the method ?
It's not javascript.
A lot of answers heere seem to indicatie that it is not possible because of the current syntax and rule. But the question is about changing them. I think it would be possible, but a little complicated and resulting in an awkward (error-prone) syntax. Like
var f() { return new { A = "*", B = 1 }; }
var x = f();
The question is whether this adds sufficient value to the language to make it worth it.
At least up to 3.5, anonymous types are actually resolved at compile time, and this would be impossible (or quite hard) to do with anonymous method signatures.