views:

143

answers:

3

I got that line of code and it's getting duplicated a lot

myString = If(myObj1.myProp Is Nothing, "", If(want = "abr", myObj1.myProp.abr, myObj1.myProp.desc))

that line x n, just change "myObj1" to "anything" and "myProp" to "anything"

I tried this

Public Function getDesc(Of t)(ByVal obj As t) As String
    Return If(obj Is Nothing, "", If(want = "abr", obj.abr, obj.Desc))
End Function

the problem here is t doesn't know that it got abr / desc properties

+4  A: 

Create a method, and pass in the variable parts as arguments.

Create the method as such, so that the method knows that T has those specific properties. Put a constraint on your generic type (define that T should inherit some kind of interface in which those properties are defined).

In C#, you can do it like this. (It can be done in VB.NET as well, but I don't know the syntax).

public string GetDesc<T> ( T obj ) where T : ISomeInterface
{
   if( obj == null ) 
     return String.Empty;

   if( obj.abr == ... )
    ...
}

The interface 'ISomeInterface' should then define the abr and Desc properties. You will also have to make sure that the types you use in your method call, implement this interface, otherwise you'll get a compile-error.

I believe that, in VB.NET, it would look something like ths:

Public Function getDesc(Of t As ISomeInterface )(ByVal obj As t) As String
    Return If(obj Is Nothing, "", If(want = "abr", obj.abr, obj.Desc))
End Function
Frederik Gheysels
look at my edit
Fredou
I'm half there now, thanks for the idea of using an interface, what I have to do now is figuring out how I will fix that compile-error without screwing up everything :-)
Fredou
my object are linq2sql one, do you know a way to fix that compile-error, for now I have no idea.
Fredou
A: 

A method is the way to go. You can then replace this line of code in your program with the method name and pass in the relevant parameters. Also means that if you need to change this line of code sometime in the future, you only have to change it inside the method and not at every point in the code where the line appears.

Davie
+1  A: 

You could create an interface for all classes with an abreviation and description, something like:

Public Interface IObjectWithDescription

    Property Abreviation As String
    Property Description As String

End Interface

Then implement that interface for all objects with these properties. Then you could have:

Public Function getDesc(ByVal obj As IObjectWithDescription, want As String) As String
    Return If(obj Is Nothing, "", If(want = "abr", obj.Abreviation, obj.Description))
End Function

I advise that you find a better name for the interface though, I don't know enough details about your problem to find one ;-)

Meta-Knight
what if the object is an entityref from linq2sql?
Fredou