user12011474
user12011474

Reputation:

How do I create nested properties? C#

As far as I read, creating nested properties don't seem to be possible in c#.

What I want to do is:

Callout callout = new Callout();
callout.Font.Size = 200;

This is the code I currently have

class Callout
{
     // nested properties
}

I know how to create properties, but how do I create a nested property?

Upvotes: 0

Views: 180

Answers (3)

John Wu
John Wu

Reputation: 52240

If you really don't want to implement a separate class or struct, here's a tricky way to do what you are asking.

Note: Tricky != Recommended

class Callout : Callout.IFont
{
    public interface IFont
    {
        int Size { get; set; }
    }
    protected int _fontSize = 0;

    int IFont.Size
    {
        get
        {
            return _fontSize;   
        }
        set
        {
            _fontSize = value;
        }
    }

    public IFont Font => this;
}


var callout = new Callout();
callout.Font.Size = 100;

Upvotes: 1

petesramek
petesramek

Reputation: 3208

public class Callout {

    public Font Font {get;}
}

public struct Font {
    public Font(int size) {
        Size = size;
    }

    public int Size {get;}
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062780

class Callout {
    public Font Font {get;} = new Font();
}
class Font {
    public int Size {get;set;}
}

Upvotes: 2

Related Questions