I was looking at this question, and it made me wonder.
Whenever I define a class with auto properties,
// Example A
public class MyObject
{
public int MyInt { get; set; }
}
the JIT compiler will convert it to similar to this:
// Example B
public class MyObject
{
private int _MyInt;
public int get_MyInt()
{
return _MyInt;
}
public void set_MyInt(int value)
{
_MyInt = value;
}
}
So you could hypothetically write something like the following:
// Example C.1
public class MyObject
{
public int MyInt { get; set; }
public void set_MyInt(string value)
{
MyInt = int.Parse(value);
}
}
Or something potentially like this:
// Example C.2
public class MyObject
{
private int _myInt;
public int MyInt
{
get { return _myInt; }
set
{
_myInt = value;
}
set(string)
{
_myInt = int.Parse(value);
}
}
}
And have this functionality exist without compiler errors.
// Example D
public void DoSomething(string someIntegerAsAString)
{
var myObject = new MyObject()
{
MyInt = someIntegerAsAString
};
}
What's stopping the compiler from saying code such as Example D, where the desired result is inferred and it works correctly and expected? The functionality is there, shown in Example B.
Is this something that's against how the language designers have designed the language to work and behave?
You cannot overload a property: A property cannot be overloaded. It means that one can only put a single get and set accessor and mutator in a class respectively. The program given below shows what happens when we give more than one get accessor in the same class.
Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. C# can distinguish the methods with different method signatures.
You can, indeed, do this...
public class MyObject
{
public int MyInt { get; set; }
public void set_MyInt(string value)
{
MyInt = int.Parse(value);
}
}
...inspite of the obvious performance overhead of converting a string to an int.
This will not work:
public class MyObject
{
private int _myInt;
public int MyInt
{
get { return _myInt; }
set
{
_myInt = value;
}
set(string)
{
_myInt = int.Parse(value);
}
}
}
...because C# doesn't support setter
overload. However, you could achieve something kind of similar with implicit type conversion, but it has to be implemented on your own types. Integer is a value type so it's inherently sealed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With