Just learned generics...
I just learned generics and have a problem that i tried googling but still couldnt solve.
I have a person class
And a user class that i want to inherit the Person class.
11 Replies
i am still a very beginner so i might have some easy mistakes in my code
When inheriting a generic class, you need to specify the generic parameter
either by making your child class also be generic and passing the generic, or by setting it concretely
your constraint here doesnt really make sense either - you are saying
T
needs to be a Person<T>
oh thats my bad, i meant it to be everything under person
thats fine in itself, but given that you are using
T
to make two properties of type T, called "Name" and "Pass(word?)"...but it sends an eror so i thought i had to mention person as the generic in every instance
here for example
User
specifies that T is string for all users
so name and pass become public string Name { get; set; }
etc for User
I think i do get it
Yes it worked thank you
although in program.cs when i try to create an object and insert the property of name and pass (which is short for password) it seems as if there isnt anything to fill
the error is that it doesnt have a constructor to fill in the argument
so 2 errors here
Person<User>
seems weird in the first place
and second, the compiler is right, you have not made any constructors
so there is no ctor that takes in a parameter at all
Remember, the T
is a "placeholder". whatever you give there replaces all T
in the class
so Person<User>
has a Name
property of type User
thats pretty weird
meaning your structure becomes person.Name.Name
if you want to get a users username
or person.Pass.Name
? we dont know
the structure is just very confusingYeah looks like you'd be better off avoiding generics for a scenario like this, you're probably better off looking at interfaces for something - similar -.
E.g.
This way you could do something like:
Generics would be useful if your types were immutable e.g.:
This might not be 100% as just typing it out here, but you could invoke it like this: