0

I got an error CS0305 with this piece of code. Is there a good way to do this ?

public class Filtre<T> : List<KeyValuePair<Filtre.Methode, object>>
{
    public enum Methode
    {
        Id,
        Keyword
    }
}  
atiyar
  • 7,762
  • 6
  • 34
  • 75
cyrianox
  • 184
  • 1
  • 12
  • [https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0305](https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0305) – Fabio Mar 05 '21 at 05:25
  • thanks, already read it. Posted because i can't find the correct syntax – cyrianox Mar 05 '21 at 05:26
  • 3
    You might want to move the enum outside of the class. Note that it currently doesn't belong to the `Filtre` class. It belongs to the generic `Filtre` class. So, in order to access it, you'd need to use `Filtre.Methode`. As I said, it might be a better idea to move it outside the class or to a different class (a `static` one, maybe). – 41686d6564 stands w. Palestine Mar 05 '21 at 05:31
  • @41686d6564 : yeah, it's working outside, and i'll do it that way if i can't find a way to keep the enum inside the class – cyrianox Mar 05 '21 at 05:33
  • It makes no sense to embed a `public enum` inside a generic, it adds nothing as all variations of `Filtre<>` will share the _same definition_. As mentioned above, move the definition _outside_ –  Mar 05 '21 at 05:44
  • Why do you want to inherit from `List` anyway? [Favour composition over inheritance](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – Charlieface Mar 05 '21 at 10:52

1 Answers1

2

If you really want to keep the enum inside Filtre<T>, then change the class signature as -

public class Filtre<T> : List<KeyValuePair<Filtre<T>.Methode, object>>
{
    public enum Methode
    {
        Id,
        Keyword
    }
}

But does that make any sense? Think about it, does the value of T by any means affect the enum Methode? No. Rather its adding unnecessary friction in code.

Also, you cannot declare the enum as anything less accessible than public, because then you will be making the base class List<KeyValuePair<Filtre<T>.Methode, object>> less accessible than Filtre<T>.

So, it will be better to declare the enum outside, and simplify the class signature -

public enum Methode
{
    Id,
    Keyword
}

public class Filtre<T> : List<KeyValuePair<Methode, object>>
{
    //
}
atiyar
  • 7,762
  • 6
  • 34
  • 75