Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a property name and a method name be same in C#? [duplicate]

Tags:

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 ?

like image 403
Brij Avatar asked Mar 20 '13 11:03

Brij


People also ask

Can a class and method have the same name C#?

Yes, It is allowed to define a method with the same name as that of a class.

How property is different from method in C#?

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.

Can properties be private in c#?

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.

When to use properties in c#?

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.


1 Answers

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.

like image 124
Matthew Watson Avatar answered Oct 10 '22 19:10

Matthew Watson