Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the method naming for property getters/setters standardized in IL?

I have the following two methods that I am wondering if they are appropriate:

public bool IsGetter(MethodInfo method)
{
    return method.IsSpecialName
        && method.Name.StartsWith("get_", StringComparison.Ordinal);
}

public bool IsSetter(MethodInfo method)
{
    return method.IsSpecialName
        && method.Name.StartsWith("set_", StringComparison.Ordinal);
}

While this code works, I'm hoping to avoid the portion that checks the StartsWith and programmatically get the naming convention. Basically, are there any .NET 4.5 classes that are able to see if the MethodInfo is a property getter/setter?

like image 204
myermian Avatar asked May 23 '13 16:05

myermian


People also ask

What should I name my getters and setters?

For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

Can getters and setters have the same name?

You can only have one getter or setter per name, on an object. (So you can have both one value getter and one value setter, but not two 'value' getters.)

When creating getters What is the naming convention?

The getter should start with 'get', followed by the member name, with its first letter capitalized. Also the latest conventions I heard of, say that we should avoid multiple capital letters one after another.

What is property getters and setters?

What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.


1 Answers

A property method has three extra characteristics, compared with a normal method:

  1. They always start with get_ or set_, while a normal method CAN start with those prefixes.
  2. The property MethodInfo.IsSpecialName is set to true.
  3. The MethodInfo has a custom attribute System.Runtime.CompilerServices.CompilerGeneratedAttribute.

You could check on 1, combined with option 2 or 3. Since the prefixes are a standard, you should not really worry about checking on it.

The other method is to enumerate through all properties and match the methods, which will be much slower:

public bool IsGetter(MethodInfo method)
{
    if (!method.IsSpecialName)
        return false; // Easy and fast way out. 
    return method.DeclaringType
        .GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) 
        .Any(p => p.GetGetMethod() == method);
}
like image 107
Martin Mulder Avatar answered Sep 30 '22 04:09

Martin Mulder