sanchop22
sanchop22

Reputation: 2809

Return base class in C#

How can i return data that is in base class form?

A aclass = new A();
B bclass = aclass.GetB();

does not work.

public class B
{
    protected string str1;
    protected string str2;
}

public class A:B
{
    public A()
    {
         base.str1 = "A";
         base.str2 = "B";
    }

    public B GetB()
    {
        return base;
    }
}

Upvotes: 2

Views: 13217

Answers (3)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

GetB() is completely unnecessary. B bclass = aclass; is sufficient as aclass is already a B.

Upvotes: 11

daryal
daryal

Reputation: 14919

I strongy advise not to use the following code and instead change the behavior of your class but the answer is the following:

public B GetB()
{
    return this as B;
}

but instead writing a unique method for returning the object casted to the base class you may use the following;

public class B
{
    protected string str1;
    protected string str2;
}

public class A : B
{
    public A()
    {
        str1 = "A";
        str2 = "B";
    }
}

and you can use as the following;

A a = new A();
B b = a;

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258618

I'm no C# expert, but return this; should work. I really don't see the point in doing this though.

Upvotes: 5

Related Questions