I have a class that contains two methods like these:
public String getFoo(Int32 a) { return getBar(a, 'b', null); } public String getBar(Int32 a, String b, Int32 c) { //do something return ''; }
However when I compile my class I get two errors:
- The best overloaded method match for getBar(int,string,int) has some invalid arguments
- Argument ‘3’: cannot convert from ‘
<null>‘ to ‘int’
I think I understand why I’m getting this error: the compiler doesn’t know at the time of compilation what the real type of the object is. Can someone confirm if I’m correct about the cause of the error or point out the real reason?
More importantly, can I design my code this way? If so, what do I need to do to fix the errors? My reason for designing my class this way is because I don’t want to duplicate the code in getBar, in getFoo. The two methods do essentially the same thing except one takes a third parameter.
Thanks.
In .NET, there is a distinct concept between reference types and value types.
A reference type is an object that is allocated on the heap (It will be a subclass of System.Object). All that is on the stack is a pointer to this object. Because of that, it is perfectly valid to store a null pointer.
A value type is an object that is allocated on the stack, it will be a subclass of System.ValueType. Because a value type lives on the stack, when you pass its value to a function, you pass the entire contents of the object.
Value types cannot be null.
Most C# primitive types are value types. String is a special type of primitive that is actually a reference type.
In .NET 2.0, MS added the ability to enclose a generic type inside of a struct so that it could simulate a nullable type. What really happens is that the logic inside of the Nullable<T> struct is emulating a null for you.
They expressed it using a syntax shortcut by adding a question mark to the type, for example:
etc…
If you don’t like the int? syntax, you can always use Nullable<SomeType>
As a side note, I prefer to add an overload when doing what you are doing, just to make the syntax nicer.