Reputation: 8102
Ok, this question has been answered in SO and here is the How to pass value to base constructor
public SMAPIException( string message) : base(message)
{
TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
// code removed for brevity sake.
}
But suppose I want to manipulate the "message" info and then set the base class constructor, then how to do it.
Pseudo code below:
public SMAPIException( string message) : base(localizedErrMessage)
{
TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
// code removed for brevity sake.
}
// So basically I want the localizedErrMessage to be sent instead of message to base class constructor, is it possible? Please guide me.
Upvotes: 5
Views: 4110
Reputation: 5113
This should work:
public class SMAPIException : Exception
{
public SMAPIException(string str) : base(ChangeString(str))
{
/* Since SMAPIException derives from Exceptions we can use
* all public properties of Exception
*/
Console.WriteLine(base.Message);
}
private static string ChangeString(string message)
{
return $"Exception is: \"{message}\"";
}
}
Note that ChangeString
has to be static
!
Example:
SMAPIException ex = new SMAPIException("Here comes a new SMAPIException");
// OUTPUT //
// Exception is "Here comes a new SMAPIException"
Inspecting your BaseType
:
// Summary:
// Initializes a new instance of the System.Exception class with a specified error
// message.
//
// Parameters:
// message:
// The message that describes the error.
public Exception(string message);
Calling base(string message)
is the same as new Exception("message")
So you can get the passed value using the Message
-Property.
BUT ! this only works if SMAPIException
does not hide it's base member new string Message {get; set;}
!
Upvotes: 6
Reputation: 7204
You can call your static method in the parameter list of the base class constructor.
public SMAPIException( string message)
: base(TranslationHelper.GetTranslationHelper.GetTranslatedMessage(message, ""))
{
}
Upvotes: 0
Reputation: 1251
Have a static factory method, and make the constructor private:
class SMAPIException
{
private SMAPIException(string message) : base(message)
{
// whatever initialization
}
public static SMAPIException CreateNew(string message)
{
string localizedErrMessage;
// do whatever to set localizedErrMessage
return SMAPIException(localizedErrMessage);
}
}
You can then use:
SMAPIException localizedEx = SMAPIException.CreateNew("unlocalizedString");
Upvotes: 3