lails
lails

Reputation: 105

How Get data from a derived class?

Get data from a derived class.. My samples.

public class Maintest
{
    public string name = "2";
}

public class test : Maintest
{
    string bla = name;
}

or

public class test : Maintest
{
    test child = new test();
    string bla = child.name;
}

Please reply or Share a link to explore

For example there is the main class and I have a derived class that will output data of the first class. As an example, I just wanted to pass the value of the derivative in the main class. For a proper understanding

Upvotes: 1

Views: 81

Answers (2)

Chase Florell
Chase Florell

Reputation: 47427

If you return the field from a property, it might look a little something like this.

using System;

public class Program
{
    public void Main()
    {
        var test = new Test();
        Console.WriteLine(test.greeting);
    }
}

// make this abstract if you're never directly instantiate MainTest
public abstract class MainTest
{
    public string name = "world";
}

public class Test  : MainTest
{
    public string greeting {get { return "Hello " + name;}}
}

http://dotnetfiddle.net/R8kwh3

Also, you can enforce a contract by doing something like

public abstract class MainTest
{
    public string name = "world";
    // create an abstract property to ensure it gets implemented in the inheriting class
    public abstract string greeting {get; private set;}
}

public class Test  : MainTest
{
    public override string greeting {get { return "Hello " + name;}}
}

Upvotes: 1

Boris Parfenenkov
Boris Parfenenkov

Reputation: 3279

Maybe you want get data in method? Therefore, you can use this:

public class test : Maintest
{
    public string GetData()
    {
        return name;
    }
}

Upvotes: 0

Related Questions