user8931966
user8931966

Reputation:

Visual C#, unable to use my struct as a property

I made a user control which contains several self-made properties. When I tried to set the property type to build-in structures such as Point or Size, it showed up fine!

public Point myProperty { get; set; }

enter image description here

But when I set it to my own struct, it doesn't work! It becomes PriceInput.PriceInput+myStruct (PriceInput is the namespace)

enter image description here

myStruct looks like

    public struct myStruct
    {
        public int A {get;set;}
        public int B {get;set;}
        public int C {get;set;}
        public int D {get;set;}
    }

Why!? What do I miss!? Thank you very very much for your help!

Upvotes: 0

Views: 79

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Per default every class or struct will just print out its own name within any output, be it the console or whatever. In your case this is PriceInput.PriceInput+myStruct. That´s because the runtime has no knowledge on what to print. Imagine you´d have more properties in your struct. Should all go the output? Or just a few ones? How should they be formatted? That´s why the runtime decides to not to guess and simply prints out the class`/structs name.

To avoid this (and that´s what Point also does), override the ToString-method in your struct:

public struct myStruct
{
    public override string  ToString()
    {
        return "Whatever";
    }
}

If you do not override this method, you get the base-implementation from object, which just returns the type-name as shown above.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460018

You should override ToString if you want a meaningful output:

public struct myStruct
{
    public int A {get;set;}
    public int B {get;set;}
    public int C {get;set;}
    public int D {get;set;}

    public override string ToString()
    {
        return $"{A}:{B}:{C}:{D}";
    }
}

Object.ToString just returns the the fully qualified name of the object's type.

Upvotes: 1

Related Questions