user673453
user673453

Reputation: 167

How to get the name of the objects of a class

How can I get the names of the TextLine objects of the PageHeader class(textline1, textline2) in a form class and display it in the form. The classes are as below

class Textline
{
    string text;
    string name;
}

class PageHeader
{
    TextLine textline1;
    TextLine textline2;
}

Upvotes: 2

Views: 159

Answers (3)

Anton Semenov
Anton Semenov

Reputation: 6347

Suppose you have instance pgHead of PageHeader. You can obtain name of textline1 this way:

pgHead.textline1.name

but in this sample you should add public key words before all members of your classes

[EDIT] If you want to obtain only field names of PageHeader type try out reflection as below:

var items = typeof(PageHeader).GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);

string fieldsNames = "";

foreach (System.Reflection.FieldInfo fld in items)
{
    fieldsNames += fld.Name + "\n";
}

MessageBox.Show(fieldsNames);

Upvotes: 2

Mario The Spoon
Mario The Spoon

Reputation: 4859

If you go with Barna's answer, do not forget to set the Name property. I would introduce a matching constructor:

class TextLine
{
    private string text;
    private string name;

    public TextLine( string name )
    {
       this.name = name;
    }

    public string Name
    {
        get {return name;}
    }
}

And then use it with:

TextLine tl = new textLine("MyName");
System.Console.Out.Writeln( "name of tl: {0}", tl.Name );

hth

Mario

Upvotes: 1

Barna
Barna

Reputation: 113

I guess this is what you need:

class Textline
{
    string text;
    string name;
    public string Name { get { return name; } }
}

and then:

textline1.Name

Upvotes: 0

Related Questions