I've done some research and found nothing so far.
public var Method()
{
//Do something
}
You can use dynamic.
public dynamic Method() {
}
..however, you should probably re-think your design. Your consumers of this method will not know what type you pass out. Therefore, you may as well split it into individual methods with expected types. The amount of logic you'll write just to make sure what you have returned out is what you expect means splitting the functions with proper types is less work.
Also, dynamic is not the same as var. dynamic means "anything".. var means "whatever is declared on the other side of this assignment". Since you can't use var in the context of a method return value (it isn't an assignment).. the only option is dynamic. When you can return "anything" out of a method, your code is very open to bugs.
TLDR: You're setting yourself up for a headache. Don't do it.
No, there isn't. Per the specification, using the identifier var for implicit typing is only allowed in the context of a local variable declaration. Eric Lippert's article on why var is not valid for fields raises a number of issues with implementing it outside the local variable context, which apply to using it in method signatures as well. Two issues are raised:
It significantly complicates analysis of types at the top level since many of the compiler's algorithms for overload resolution were written assuming all top level types are known.
The inferred type of the var field could be an anonymous type and there is no standard for how these types can be unified across assemblies.
As is pointed out in the article, these are not insurmountable problems but they indicate that there could be significant costs to implementing var outside a local variable declaration. The article was written in 2009, perhaps it is easier to implement in the Roslyn compiler.
From the documentation:
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
If you have a function with a public var Method() signature, The return type is not expressed implicitly, and therefore the compiler cannot determine the type on it's on.
So, the answer to you question is: No, such a signature will not compile....
Related
I'm using the ILNumerics library for a project, but I found that variables declared with "var" will sometimes change value in the middle of computation, for example:
// A is a matrix
var x = A[full, 0];
double xNorm = (double)norm(x);
The x is valid in the first line, however causes "NullReference" exception after execution of the second line.
But If I do:
// A is a matrix
ILArray<double> x = A[full, 0];
double xNorm = (double)norm(x);
The computation will be fine. So what is the problem here? Does that mean we need to be cautious when using "var"?
It's not a bug - it's a feature :)
The var keyword is not allowed to be used in this context. This is part of a collection of three ILNumerics specific rules. It can also be found in the guickstart guide.
In short, the ILNumerics memory management relies heavily on implicit type conversions. All functions / properties return array types of ILRetArray<T>. These return types are volatile by design: they dispose off their storage after the first use. Always. So one can give them to some other function or query some information from them. But you would rather not try to access it a second time!
However, the only way to access such an object twice would be to have a reference (a regular local variable) around. ILNumerics specifies that all local variables must be of type ILArray, ILLogical or ILCell. Once you assign an array to a variable of one of those types, implicit type conversions kick in and 'turn' the volatile return object into something more stable and safe to access several times.
This is why the var keyword is forbidden in C# with ILNumerics. Similar thing for Visual Basic, where you also must declare the type of local array variables explicitly. I once made a blog post about the issue:
http://ilnumerics.net/blog/why-the-var-keyword-is-not-allowed-in-ilnumerics/
When declared with var, x is referring to something of type ILRetArray'1; if declared as ILArray<double>, it's ILArray'1. Those are sibling subclasses of a common base (ILDenseArray). A's type is ILArray<double> and its array-indexing operator returns type ILRetArray<ElementType>.
There are implicit conversion operators going both ways here between those two classes.
It looks like when A[full, 0] is assigned to a variable whose type is left up to type inference, the compiler makes it the return type of A's array indexing operator: ILRetArray<ElementType>. But if you declare x's type explicitly as ILArray<double>, an implicit conversion operator is invoked and you get a different actual object.
Then you pass it to norm, which expects ILInArray, and yet another implicit conversion operator is invoked. And there's a bug in that one. It breaks something in the internal state of ILRetArray. Try this line before the call to norm:
var d = (ILInArray<double>)x;
...and it will have the same effect on x as the call to norm did. So it's that conversion.
I haven't downloaded the source to ILNumerics to identify the details of the bug. It's possible that this is meant to be a forbidden operation, in which case I'd wish they had better error reporting (UPDATE see #HaymoKutschbach's answer below: This is in fact the case; ILRetArray is a volatile type by design, intended to be valid only until the first implicit conversion operator is called on it).
It might be fun to submit a bug report to ILNumerics and see what you hear back (UPDATE: There's a guy from ILN in this thread, so never mind).
But in answer to your question: You do need to be a bit cautious when using var; avoid it when there's any possibility of ambiguity. You need to be especially cautious when implicit conversion operators are involved. I had forgotten those things even existed in C#. I'm not fond of them. Of course the bug wasn't caused by their use of an implicit conversion operator; it's just a bug. But the operators vastly and invisibly confused the issue of what was going on in the code. I prefer type conversions to be visible in the source.
Thanks for posting this, it was fun.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the point of the var keyword?
Why does c# need the "var" identifier for type inferred type variables?
I mean what is the problem with just leaving it off:
a = 1;
//vs
var a = 1;
Reading Programming in Scala:
"Type variable" syntax you cannot simply leave off the type - there would be no marker to start the definition anymore.
But what is the different between leaving it off in the a:Int or int a?
At least one reason that comes to mind is that it forces the programmer to declare their intent to introduce a new variable, as opposed to assigning to an existing variable. This enables the compiler to detect numerous common coding errors.
Consider this:
class Foo
{
int a;
void Bar()
{
var a = 1;
}
}
Without the var keyword, the assignment would be to the class member a.
var introduces unambiguously a new local variable.
You have to define a variable before you use in C#. Sure, the compiler could detect when it reaches
a = 1;
That a had not yet been defined and so define the variable and assign it the value of 1. However, it could lead to other issues where you have:
MyOwnClass myVeryLongVariableNameThatIsUsedAllOverThePlace = new MyOwnClass();
myveryLongVariableNameThatIsUsedAllOverThePlace = input.GetNewClass();
Now you have 2 variables, where you thought you had one.
From MSDN:
It is important to understand that the
var keyword does not mean "variant"
and does not indicate that the
variable is loosely typed, or
late-bound. It just means that the
compiler determines and assigns the
most appropriate type.
The idea is to keep the robustness of C# by preventing accidental Implicitly Typed Local Variable.
Technically, there's really no need. Other languages allow you to combine declaration and assignment with no special keywords.
If a = 1 was valid syntax for both assignment and declaration, though, code could become very confusing which is, I believe, why C# requires at least var.
keyword will tell the compiler not to try resolve the identifier outside the scope of the method.
Can C# work without it? Yes, but this enforces a discipline which is required for a strongly typed language.
Different programming languages are designed to suit different purposes. C# is designed for writing large-scale high-reliability software. Part of its approach to this is using explicitly-declared staticly-typed variables. The ability to infer variable types was required by the addition of anonymous objects, which were required for LINQ query expressions. The existance of these things does not alter the fact that variables must be explicity-declared and their types established at compile-time (modulo dynamic, of course).
Explicit variable declaration removes a large class of bugs that sometimes occur in programs written in languages that do not require variable declarations.
In my humble opinion, I think it is safe to assume that they didn't (or couldn't) modify the C# grammar so significantly as to allow the omission of a (type or "var") token in the variable declaration when they added type inference to the language. (This would have consequences for function declarations also.)
I think such a change would have a ripple effect across the entire grammar and wreck backwards compatibility.
Maybe F# is a by-product of the grammar being changed at such a fundamental level ;)
This question already has answers here:
Implicit typing; why just local variables?
(6 answers)
Closed 8 years ago.
class A
{
A()
{
var x = 5; // this is allowed
}
var _x = 5; // the compiler is unhappy
}
I guess the compiler must be able to deduce the type for the member variable just the same way it does it for the local one. So what's the difference?
Eric Lippert answered your question right here: Why no var on fields?
Basically, for the general case it would require re-writing the C# compiler, as the way it currently does type inference would not work for cycles of var field variable assignments.
The var keyword was designed for anonymous types, which can only be used inside of a method.
Also, you're wrong; the compiler cannot always deduce a var field.
What happens if you compile the following:
class A {
public readonly var value = B.value;
}
class B {
public readonly var value = B.value;
}
This situation is impossible to recreate with local variables, since a variable cannot be referenced before it's defined.
The general problem here is that you're asking the compiler to consume type information while it's still generating that information.
Eric Lippert explains in greater depth.
I see two reasons:
It might be desirable to make the declaration of types in a public interface explicit
It's hard to implement. The C# compiler compiles in multiple phases.
At first it parses everything apart from method bodies so it knows about everything outside of function bodies. Then it can use that information to compile method bodies individually. What happens while compiling one method body hasn't much effect on what happens when compiling other method bodies.
If you could use var for fields the expression body of the field initializer would affect the type of the field and thus many other methods. So it doesn't fit the compiler design well.
This is a guess, but initialization of class-level fields must be done as part of the initialization (constructor) process for a Type, whereas initialization of a method-level variable happens when the method's stack frame is constructed. Perhaps the distinction is related to how these processes are compiled (how their implementation is created) inside the framework.
I'm very excited about the dynamic features in C# (C#4 dynamic keyword - why not?), especially because in certain Library parts of my code I use a lot of reflection.
My question is twofold:
1. does "dynamic" replace Generics, as in the case below?
Generics method:
public static void Do_Something_If_Object_Not_Null<SomeType>(SomeType ObjToTest) {
//test object is not null, regardless of its Type
if (!EqualityComparer<SomeType>.Default.Equals(ObjToTest, default(SomeType))) {
//do something
}
}
dynamic method(??):
public static void Do_Something_If_Object_Not_Null(dynamic ObjToTest) {
//test object is not null, regardless of its Type?? but how?
if (ObjToTest != null) {
//do something
}
}
2. does "dynamic" now allow for methods to return Anonymous types, as in the case below?:
public static List<dynamic> ReturnAnonymousType() {
return MyDataContext.SomeEntities.Entity.Select(e => e.Property1, e.Property2).ToList();
}
cool, cheers
EDIT:
Having thought through my question a little more, and in light of the answers, I see I completely messed up the main generic/dynamic question. They are indeed completely different. So yeah, thanks for all the info.
What about point 2 though?
dynamic might simplify a limited number of reflection scenarios (where you know the member-name up front, but there is no interface) - in particular, it might help with generic operators (although other answers exist) - but other than the generic operators trick, there is little crossover with generics.
Generics allow you to know (at compile time) about the type you are working with - conversely, dynamic doesn't care about the type.
In particular - generics allow you to specify and prove a number of conditions about a type - i.e. it might implement some interface, or have a public parameterless constructor. dynamic doesn't help with either: it doesn't support interfaces, and worse than simply not caring about interfaces, it means that we can't even see explicit interface implementations with dynamic.
Additionally, dynamic is really a special case of object, so boxing comes into play, but with a vengence.
In reality, you should limit your use of dynamic to a few cases:
COM interop
DLR interop
maybe some light duck typing
maybe some generic operators
For all other cases, generics and regular C# are the way to go.
To answer your question. No.
Generics gives you "algorithm reuse" - you write code independent of a data Type. the dynamic keyword doesn't do anything related to this. I define List<T> and then i can use it for List of strings, ints, etc...
Type safety: The whole compile time checking debate. Dynamic variables will not alert you with compile time warnings/errors in case you make a mistake they will just blow up at runtime if the method you attempt to invoke is missing. Static vs Dynamic typing debate
Performance : Generics improves the performance for algorithms/code using Value types by a significant order of magnitude. It prevents the whole boxing-unboxing cycle that cost us pre-Generics. Dynamic doesn't do anything for this too.
What the dynamic keyword would give you is
simpler code (when you are interoperating with Excel lets say..) You don't need to specify the name of the classes or the object model. If you invoke the right methods, the runtime will take care of invoking that method if it exists in the object at that time. The compiler lets you get away even if the method is not defined. However it implies that this will be slower than making a compiler-verified/static-typed method call since the CLR would have to perform checks before making a dynamic var field/method invoke.
The dynamic variable can hold different types of objects at different points of time - You're not bound to a specific family or type of objects.
To answer your first question, generics are resolved compile time, dynamic types at runtime. So there is a definite difference in type safety and speed.
Dynamic classes and Generics are completely different concepts. With generics you define types at compile time. They don't change, they are not dynamic. You just put a "placeholder" to some class or method to make the calling code define the type.
Dynamic methods are defined at runtime. You don't have compile-time type safety there. The dynamic class is similar as if you have object references and call methods by its string names using reflection.
Answer to the second question: You can return anonymous types in C# 3.0. Cast the type to object, return it and use reflection to access it's members. The dynamic keyword is just syntactic sugar for that.
I am not sure when I should use anonymous types instead of local variables in C#.
I have:
string fullMessage // This is the full message including sender and recipient names
string sender = GetMessagePart(fullMessage, "from");
string recipient = GetMessagePart(fullMessage, "to");
//do some stuff and deliver the message
Should I use:
var msg = new {
sender = GetMessagePart(fullMessage, "from")
recipient = GetMessagePart(fullMessage, "to")
};
Instead?
Do you mean statically typed variables? Note that anonymous types are statically typed... (removed due to question edit)
There are 2 problems with C# anonymous types:
you can't expose them through a method API
you can't mutate them (the members are read-only)
If you only need to know about the data within a single method, and it is read-only, then an anonymous type is handy (and this covers a lot of cases, in reality).
If you need to mutate the data or pass it out to a caller, then use either a bespoke class, or simple variables (etc).
In the case given, I can't see a reason to use an anonymous type; if you just want the values, use the separate variable approach. If a "message" has a defined meaning, declare a Message class and populate that.
Does grouping a sender and recipient together make sense outside this method? If so, consider creating a class for them. If not, I would usually use separate local variables, but I suspect that's mostly through habit.
I suspect what we've here got is a pair of local variables which are conceptually related. The relationship may not be strong enough to deserve a full type, but it's meaningful within the method. In some ways, using an anonymous type is a very neat way of making that pairing obvious. On the other hand, if your method is long enough that it really needs that extra level of clarity, perhaps you should break it up anyway.
Note that using an anonymous type makes some refactoring techniques harder because the type is only available with the method (without a bit of hackery).
I realise that this is a wishy-washy answer, but it does strike me that there's some merit in the overall idea - it's a bit like using a tuple in a functional language.
Use local variables (i think this is what you meant) in this case.
Anonymous type should be use where you would need a standard name type but use it only for implementation purpose inside of a method. It removes the tedious work of creating a new type definition.
You would not need a type here, so don't use an anonymous type.