2

Go has a nice feature where members of a nested struct are automatically accessible via its parent struct:

// Server exposes all the methods that Logger has
type Server struct {
    Host string
    Port int
    *log.Logger
}

// initialize the embedded type the usual way
server := &Server{"localhost", 80, log.New(...)}

// methods implemented on the embedded struct are passed through
server.Log(...) // calls server.Logger.Log(...)

// the field name of the embedded type is its type name (in this case Logger)
var logger *log.Logger = server.Logger

Is the same possible in C#, for example using implicit casts?

struct B
{
    public int x;
}

struct A
{
    public B b;
}

var a = new A();

a.b.x = 1; // How it usually works
a.x = 1; // How Go works, assuming x is unambiguous 
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

2 Answers2

0

There is no such concept in C#. You can add such properties by yourself, but it will be very confusing for other developers who see your code.

struct B
{
    public int x;
}

struct A
{
    public B b;
    public int x {
        get { return b.x; }
        set { b.x = value; }
    }
}

}

var a = new A();

a.b.x = 1;
a.x = 1;

However if you switch to classes instead of structs - you can have similar behavior using inheritance:

class B
{
    public int x;
}

class A : B
{
}

var a = new A();
a.x = 1;
Pavel Morshenyuk
  • 10,891
  • 4
  • 32
  • 38
0

An embedded Golang struct can be seen as a sort of "inheritance". If you want simulate this behaviour in C# you should use a class instead of struct (here if you want know the difference between struct and class).
Something like this:

public class A {
    public int X {get; set;}
}
public class B : A{
    B : base() {}
}
...
var a = new B();
a.X = 24;
Community
  • 1
  • 1
Tinwor
  • 7,765
  • 6
  • 35
  • 56
  • That is true, but I would rather use a compositional style in C#. Mixins, for example, are much nicer with this syntactic-sugar. – sdgfsdh Feb 03 '17 at 11:04