How to switch between "possible" type of an object?
.net, c#, switch-statement, types
Solution
You can also refactor this with interfaces
public interface IHasUri
{
public Uri GetUri();
}
and implement this interface in all you hierarchy. Than you can use
public Uri GetUri(object obj)
{
IHasUri hasUri = obj as IHasUri;
if(hasUri != null)
Uri uri = hasUri.GetUri();
// bla bla bla
}
Problem
Possible Duplicate: C# - Is there a better alternative than this to ‘switch on type’? My company legacy code has something as follow ``` public override Uri GetUri(object obj) { if ((obj is Entry) || (obj is EntryComment)) { // } if (obj is Blog) { // } // if obj is blah blah blah } ``` This method is just ugly. I want to refactor it, but I don't know a technique to iterate over "possible" types that obj can be. How can I refactor this? Thank you.
Related problems
- Switch case on type c#
- C# switch on type
- How to use switch-case on a Type?
- What is quicker, switch on string or elseif on type?
- Is there a better alternative than this to 'switch on type'?
- Is there any benefit to this switch / pattern matching idea?
- Best way to switch behavior based on type
- Is there a better alternative than this to 'switch on type'?