Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing properties of an inherited object in C#

If I have a complex object, can I inherit from it and remove or ignore certain properties?

If you don't care why I want to do this, feel free to just submit an answer.

If you do care, you can read this question. To summarize it, I have an object that has a single property that is not serializable, and I want to serialize the entire object. The object in question is System.Exception

To get around the problem I wanted to simply create my own JsonException object, inherit all the lovely properties of the base (System.Exception) except remove (or empty) the ugly duckling (Exception.TargetSite).

Something like:

public class MyException : Exception
{
    // Note this is not actually possible
    //      just demonstrating what I thought to do in theory
    public override System.Reflection.MethodBase TargetSite
    {
        get
        {
            return null;
        }
    }

    public MyException(string message)
        : base()
    {
    }
}

Also please keep in mind I am stuck with .NET 2.0 and really don't want to use custom serializers (like Json.NET) if I don't have to.

like image 352
Terry Avatar asked Jan 23 '26 00:01

Terry


2 Answers

See here in the "Defining Exception classes" paragraph to see how to create a custom serializable exception.

Relevant part from the article:

[Serializable()]
public class InvalidDepartmentException : System.Exception
{
    public InvalidDepartmentException() : base() { }
    public InvalidDepartmentException(string message) : base(message) { }
    public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }

    // A constructor is needed for serialization when an
    // exception propagates from a remoting server to the client. 
    protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,
        System.Runtime.Serialization.StreamingContext context) { }
}
like image 80
Sebastian Piu Avatar answered Jan 25 '26 04:01

Sebastian Piu


Did you try it without overriding the TargetSite property? I was able to do it (but not in 2.0, so I'm not sure if it will work for you like this

public class MyException : Exception
{
    public new System.Reflection.MethodBase TargetSite
    {
        get { return null; }
    }

    public MyException() : base()
    {

    }
}
like image 25
Jeff LaFay Avatar answered Jan 25 '26 04:01

Jeff LaFay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!