Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error regarding declaring generic nested class

I get a compilation errors regarding this piece of code:

Error 1 Invalid token '(' in class, struct, or interface member declaration
Error 2 Cannot use more than one type in a for, using, fixed, or declaration

Any idea why? In addition, is it possible to declare dictionary as follows?

public class S
{
        private class ObInfo<T>
        {
            private string _type;
            private T _value;

            public ObInfo<T>(string i_Type, T Value)
            {
                this._type = i_Type;
                this._value = Value;
            }

            public ObInfo() 
               {}
       }

       private static Dictionary<int,ObInfo> sObj= new Dictionary<int,ObInfo>();
}
like image 821
JavaSa Avatar asked Dec 07 '22 10:12

JavaSa


1 Answers

public ObInfo<T>(...) {

Constructors cannot take generic parameters.
Remove the <T> and everything will work.

All methods (and types) inside a class inherit that class's generic parameters; you should only create generic methods inside generic classes if the methods need a separate type parameter. (this should be avoided; it's very confusing)


Also, open generic types are not actually types; you cannot have a Dictionary<int,ObInfo> without specifying the type parameter for ObjInfo.
Instead, you can either use a non-generic interface for the dictionary, or move the type parameter to the outer class and have a separate dictionary per type parameter.

like image 160
SLaks Avatar answered May 22 '23 15:05

SLaks