What C# naming scheme can be used for Property & Member that is CLS compliant?

StackOverflow https://stackoverflow.com/questions/8282528

  •  09-03-2021
  •  | 
  •  

سؤال

Consider the following code that is not CLS Compliant (differs only in case):

protected String username;

public String Username { get { return username;} set { username = value; } }

So i changed it to:

protected String _username;

public String Username { get { return _username;} set { _username = value; } }

Which is also not CLS-compliant (has leading underscore).

Is there any common naming scheme for members/properties that doesn't violate cls compliance

هل كانت مفيدة؟

المحلول

Rather than exposing the backing field, make your property virtual so inheritors can override the functionality without exposing the implementation of your backing field.

private String username;

public virtual String Username { get { return username;} set { username = value; } }

Inherits shouldn't have to know anything your classes implementation.

See Best way to expose protected fields

نصائح أخرى

This set of rules applies to Visual Basic, but there should be a similar set for C#:

An element name in Visual Basic must observe the following rules:

It must begin with an alphabetic character or an underscore (_).

It must only contain alphabetic characters, decimal digits, and underscores.

It must contain at least one alphabetic character or decimal digit if it begins with an underscore.

It must not be more than 1023 characters long.

However, the following also applies:

Element names starting with an underscore (_) are not part of the Common Language Specification (CLS), so CLS-compliant code cannot use a component that defines such names. However, an underscore in any other position in an element name is CLS-compliant.

The above was from the MSDN Documentation.

Here is a link to the Common Language Specification documentation on MSDN which, in turn, references the ultimate arbiter of the CLS naming convention: Annex 7 of Technical Report 15 of the Unicode Standard 3.0.

MFC to the rescue. Just use the old m_ prefix:

private string m_Username;
public string Username ...

What are you trying to achieve with this?

public String Username {get; protected set};

or

private String _username;

protected void setUserName(String argUsername);
{
  if (_username != Username) // an overload of String.Compare would be better here
  {
    _username = value;
    // Do the stuff you have to do because username has changed
  }
}

public String Username {get {return _username;} protected set {setUsername(value);}}

Your way, to get CLS compliance you'd have to call you pulic and prtectred versions different names, which would be 'erm confusing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top