-4

I have below method that does work Okay but I believe we can make it better by some how getting rid of these if conditions, but not sure how?

 protected void SaveSession<T>(T sessionProperty, Management management) where T : class { string propertyType = typeof(T).Name; if (propertyType.Equals(typeof(A).Name)) { management.A = sessionProperty as A; } else if (propertyType.Equals(typeof(B).Name)) { management.B = sessionProperty as B; } else if (propertyType.Equals(typeof(C).Name)) { management.C = sessionProperty as C; } Session["mysession"] = management; } 

I am using latest C# version 7.0

6
  • Which C# version are you using? In C# 7 and later you can use a pattern matching switch statement Commented Jun 13, 2019 at 15:29
  • I am using latest C# version Commented Jun 13, 2019 at 15:30
  • Get an ArrayList property in Management. Filter with Enumerable.OfType() and add/set the sessionProperty variable. Commented Jun 13, 2019 at 15:30
  • Sounds like a good place for the strategy pattern. Other than that, don't compare type names, just compare the types directly. Commented Jun 13, 2019 at 15:34
  • @User the latest released version is 7.3. The latest preview version is 8.0. I assume you use C# 7.3, or at least C# 7? Commented Jun 13, 2019 at 15:35

1 Answer 1

3

In C# 7 and later you can use a pattern matching switch statement, eg :

switch(sessionProperty) { case A a: management.A=a; break; case B b: management.B=b; break; case C c: management.C=c; break; } 

In earlier versions you can use the is operator to check the type, eg :

if (sessionProperty is A) { management.A=(A)sessionProperty; } else if (sessionProperty is B) { management.B=(B)sessionProperty; } 
Sign up to request clarification or add additional context in comments.

9 Comments

sorry I am using I am using latest C# version 7.0
If Management could be changed, I would suggest an ArrayList property in it + .OfType<T>()
@User pattern matching works in C# 7
@bradbury9 why do that?
To reduce the amount of properties in Management. Seems like a poor design
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.