Home > Net >  C# struct in generic method
C# struct in generic method

Time:07-20

I try to do something like this:

class Program
    {
        public struct frst
        {
            public short Oversize_FrontInch;
            public short Oversize_RearInch;
            public short Oversize_RightInch;
            public short Oversize_LeftInch;
            public short HeightInch;
        }
        public struct sec
        {
            public short Oversize_FrontInch;
            public short Oversize_RearInch;
            public short Oversize_RightInch;
            public short Oversize_LeftInch;
        }
        public void DoSmth<T>() where T:struct
        { 
            T str = new T();
            str.Oversize_FrontInch = (short)2;

        }
    }

but i get "t does not contain a definition for ..." error is there any way do do this? Important thing: for the sake of rest code it is have to be struct.

CodePudding user response:

It would be great to understand more what you're trying to achieve with these seemingly unrelated structs but here's a version which compiles and runs and keeps sec and frst as structs:

DoSmth<sec>();
DoSmth<frst>();

void DoSmth<T>() where T: struct, IOversize
{ 
    T str = default;
    str.Oversize_FrontInch = (short)2;
    Console.WriteLine(str.GetType());
}


public interface IOversize 
{
    short Oversize_FrontInch {get; set;}
}

public struct sec: IOversize
{
    public short Oversize_FrontInch {get; set;}
}        

public struct frst: IOversize
{
    public short Oversize_FrontInch {get; set;}
    public short HeightInch {get; set;}
}

This prints:

sec
frst

CodePudding user response:

I am guessing you want something like this.

Struct cannot inherit so you code cannot do what you want.

You can instead use a base class and inherit data class from it.

But be aware that you need to inherit a default constructor in order to create a dataclass in a generic function.

This is a simple example for you to play with, you can edit and polish it as you want.

using System;

public class HelloWorld
{
    public class baseclass{
        public short Oversize_FrontInch;
        public short Oversize_RearInch;
        public short Oversize_RightInch;
        public short Oversize_LeftInch;
    }
    public class frst:baseclass
    {
        public short HeightInch;
    }
    public class sec:baseclass 
    { 
    }
    
    public static void DoSmth<T>() where T:baseclass, new()
    { 
        T str = new T();
        str.Oversize_FrontInch = (short)2;
        Console.WriteLine(str.Oversize_FrontInch);
    }
    
    public static void Main(string[] args)
    { 
        DoSmth<frst>();
    }
}

Edit: I saw some people suggesting using interface with struct. It is possible. However, it will box all of your value, create performance issue and create unreadable code. I would not recommanded it.

  • Related