Why is the exception message property read only?
c#, exception
Solution
`public virtual string Message`
Message is virtual - so you can easily override it in your class.
public class OPCCaException : Exception
{...
public override string Message
{
get { return "My fancy text";}
}
}
Also more standard way of doing it is to pass message via call to base class constructor:
public OPCCaException(...) : base(buildMessage(...))
{
}
Problem
Maybe the most mystifying thing to me in C# is that the Exception class's message property is read-only. Probably because I don't understand the reason for this, I am frustrated when I try to create reasonable exception classes derived from Exception. For example (and actually what I'm trying to do), I want to create an exception to raise when an attempt to connect to an OPC server. An object of type OPCException is raised if the attempt fails, but I want to give the user more information. So, I have a class named OPCCaException that takes three arguments: the return code from the original exception, the server name, and the host name. ``` public class OPCCaException : Exception { public OPCCaException(ReturnCode returnCode, string serverName, string nodeName) { if (nodeName == "") { this.Message = "Failed to connect to OPC server "+ serverName + ": " + TranslateReturnCode()"; } else { this.Message = "Failed to connect to OPC server "+ serverName + " on node " + nodeName + ": " + TranslateReturnCode()"; } } } ``` This seems to me to be a perfectly reasonable thing to do, but it won't compile because the Message property is read-only. The only way to set the message is to pass it to the base class constructor. Why can't I set it in my derived class's constructor? The only way I can think of to do any kind of processing on the arguments is to create a static class to build the message: ``` public class OPCCaException : Exception { private static string BuildMessage(<some arguments>) { string message = "some message"; return message; } public OPCCaException(ReturnCode returnCode, string serverName, string nodeName) : base(BuildMessage(returnCode, serverName, nodeName)) { } } ``` I don't know if that will compile. What is the standard way to do this?