Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Anonymous types as parameters to the functions

I need to pass to a function an object that is an anonymous type.

The thing I expect that the object contains some properties, say Name(string) and Rang(BO).

Say, I have a query like

  Dim query = From city In _container.Cities
               From street In city.Streets
               Select Name = street.Name, Rang = street.Rang
               Distinct

Now, I would like to pass each element of this query to a function.

Is it possible?

like image 201
serhio Avatar asked Dec 21 '22 09:12

serhio


2 Answers

Yes, it's possible.

You can use cast by example. Here's a sample:

class CastByExample {
    public T Cast<T>(T t, object toCast) {
        return (T)toCast;
    }

    public void M(object o) {
        var y = Cast(new { Name = "Name", Range = 0 }, o);
        Console.WriteLine(y.Name);
    }

    public void Test() {
        var x = new { Name = "John Doe", Range = 17 };
        M(x);
    }
}

You can also use reflection.

But really, how is jumping through these hoops easier than just writing a concrete non-anonymous type?

like image 93
jason Avatar answered Dec 28 '22 07:12

jason


It's not possible to state the type of an anonymous object in VB.Net. However if you're comfortable with Option Strict Off then you can use late binding. Just have the target method accept the parameter of type Object

Public Sub UseAnonymousObject(ByVal p as Object)
  Console.WriteLine(p.Name)
  Console.WriteLine(p.Rang)
End Sub

...

For Each current in query 
  UseAnonymousObject(current)
Next
like image 44
JaredPar Avatar answered Dec 28 '22 09:12

JaredPar