I have a class which contains a property:
public bool IsMandatory {get;set;}
Now I am adding a method IsMandatory(string str).
public bool IsMandatory(string str)
{
//return false;
//return true;
}
I am getting a compile time error that
the type already contains a definition for 'IsMandatory'
Can't a method name and property name be same in C# ? We use a method and property in different way, why is this giving compile error ?
Yes, It is allowed to define a method with the same name as that of a class.
Ans: A property is a named attribute of an object. Properties define the characteristics of an object such as Size, Color etc. or sometimes the way in which it behaves. A method is an action that can be performed on objects.
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.
It's a compiler error because it would cause confusion if the names could be the same. There are some cases where ambiguity could result - for example, when using Action delegates and so on, where methods do not need to have parenthesis, and when using var.
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