简体   繁体   中英

How to convert regular properties into Automatic properties C#

public class MsException : BaseException
{ 
    private readonly string _error;
    private readonly string _message;

    public MsException(int id)
    {
        var code = (Enum)errorId;

        _error = code.ToString();
        _message = code.GetNames();
    }

    public override string StatusCode => _error;
    public override string Message => _message;
}

I want to convert those properties into auto properties as C# 6 examples. How they will look like?

In BaseException I have two properties again string StatusCode and string Message .

Any help will be appreciated. I need some example how to do it.

If you have StatusCode and Message in base class. You are inheriting that base class and want to set values to base class property then you can simply assign values to that property

public class MsException : BaseException
   { 
   public MsException(int id)
      {
         var code = (Enum)errorId;

         this.StatusCode = code.ToString();
         this.Message = code.GetNames();
      }
   }

Your BaseException class might look like

public class BaseException
{
    public string StatusCode {get; set;};
    public string Message {get; set;}

}

You have some terrible mix here since you override properties that are found in BaseException which is hardly a good idea, since they already exist.

So you can just use these properties that are already there instead of creating new ones.

Perhaps you can explain why do you need this.

public class MsException : BaseException
{ 
    public MsException(int id)
    {
        var code = (Enum)errorId;

        StatusCode = code.ToString();
        Message = code.GetNames();
    }
}

Something like this may work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM