Joao Carlos
Joao Carlos

Reputation: 797

C# Assign a Variable to a Class call

Lets say I have a namespace GPS, where I can call stuff like GPS.devise.coordinates.getLoc, that would simply return the GPS coords of my devise.

How can i assign all that "GPS.devise.coordinates" verbose to a variable such as "Me"?

So I could do Me.getLoc instead.

Thanks in advance

Upvotes: 1

Views: 1439

Answers (4)

Vincent
Vincent

Reputation: 169

Assuming getLoc() is static, try using the following:

using Me = GPS.devise.coordinates;

This is often used for shortening namespaces where the classes have common names. A great example to check out would be the VSTO libraries, where most of the namespaces have an Application class.

Upvotes: 1

Mark Seemann
Mark Seemann

Reputation: 233150

If getLoc is a property, you can simply do this:

var me = GPS.devise.coordinates.getLoc;

However, I suspect that since you are asking, getLoc is a method. In that case, you can assign the method group to a delegate. In C# 3.0 you can do this:

var me = () => GPS.devise.coordinates.getLoc();

which would enable you to get the coordinates like this:

var coordinates = me();

An alternative declaration of me would be this:

Func<Coords> me = GPS.devise.coordinates.getLoc;

assuming that the return type of getLoc is Coords.

Those two declarations of me amounts to the same thing - it's just two different ways of writing it.


If you simply want a shorthand for coordinates because it has more than one method you'd like to invoke it would be very simple. Although I can't tell from your example whether coordinates is a field or a property, it doesn't matter because in both cases you simply assign the object to a new variable:

var coords = GPS.devise.coordinates;

Subsequently you can then invoke methods on the coords variable:

var loc = coords.getLoc();
var satTime = coords.getSatTime();

etc.

This will work with any version of C# (even 1.0) with the slight modification that instead of var you would need to explicitly declare the type of the variable. var is a C# 3.0 (Visual Studio 2008) feature.

Upvotes: 0

divinci
divinci

Reputation: 23149

what class would 'Me' be?

if 'Me' was say a Person class

public class Person
{
    public Person(){}

    private GPS _gps = new GPS();
    public Coords getLoc
    {
        get{
            return _gps.devise.coordinates.getLoc;
        }
    }
}


Person Me = new Person;
Coords MyLocation = Me.getLoc;

Upvotes: 0

Robban
Robban

Reputation: 6802

You could expose a property that returned it, like this:

 public Point getLoc { get { return this.device.coordinates.getLoc;}}

Upvotes: 2

Related Questions