Struct Problem

I am trying to write a similar struct to the System.Drawing.Colour struct, ie I want to be able to do the following.

BarColour bc=BarColour.White;

How do I get the BarColour struct to return a BarColour struct from within a static public property which is instantiated with a colour without the struct having a public constructor. I have the following code so far:-

struct BarColours

{

private string _colour;

public static BarColours White

{

get

{

_colour="White";

BarColours bc = this;

return bc;

}

}

public static BarColours Black

{

get

{

_colour = "Black";

BarColours bc = this;

return bc;

}

}

}



Answer this question

Struct Problem

  • Linda Shao

    Thank you.
  • Rahul Singla

    You can't access "this" in the property, because it is static, and doesn't have a "this" object.

    You seem to be trying to be unnecessarily clever. All you need is:

      1: struct BarColours
      2: {
      3:   private string _colour;
      4:   private BarColours(string c)
      5:   {
      6:     _colour = c;
      7:   }
      8:  
      9:   public static BarColours White
     10:   {
     11:     get
     12:     {
     13:       return new BarColours("White");
     14:     }
     15:   }
     16: }
     
     

    public static void Code(string[] args)

    {

    BarColours b = BarColours.White;

    // BarColours a = new BarColours("XXXX"); // 'BarColours.BarColours(string)' is inaccessible due to its protection level

    }



  • Udii

    Hi,
    you have two options:

    1- Make the _colour field static. I don't think this option fits what you want to do but it is possible to use it.

    2- Return a new object with the colour you want:
    public static BarColours White
    {
    get
    {
    BarColours bc = new BarColours();
    bc._colour = "White";
    return bc;
    }
    }

    Same for the Black property.


  • Itzhak

    You can access the _colour field even though it's private since you're in "scope" of the same object you're trying to access.

    Just the same way you can call the private constructor in the sample that James Curran provided.


  • butsona

    I can't get to the _colour field from bc as the field is private.
  • Struct Problem