Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shorten the path to a property?

Tags:

c#

For example if I have Object.ObjectTwo.Property and I don't want to clutter my code by writing that all the time, is there a way to make it shorter?

Instead of writing Object.ObjectTwo.Property = something, I would like to be able to write myVariable = something.

I couldn't find anything when I tried searching.

Edit: The member in question is a property.

like image 981
Mawkey Avatar asked Feb 15 '19 14:02

Mawkey


4 Answers

In C#, you can create shorthands for variable types at the global scope (where you put statements like using System;).

If you want to shorten Object.ObjectTwo to something simpler, you can use a using statement in the following manner:

using Object.ObjectTwo = ObjTwo;

Then, you can later call ObjTwo.Variable = someVar;, and it will act as if you had used Object.ObjectTwo.Variable = someVar;

like image 93
absoluteAquarian Avatar answered Oct 17 '22 17:10

absoluteAquarian


Maybe just declare a separate variable?

var ObjectA = Object.ObjectTwo.Variable;

Though while this is more convenient for you, on the computer side, it is one more declared variable.

like image 28
Russ J Avatar answered Oct 17 '22 16:10

Russ J


In C# 7, you can use Ref Locals. Unlike most other approaches, this approach can be used safely even when operating on structs.

This approach is only available on fields. Properties cannot be aliased using ref.

Below is an example.

struct bar
{
    public int myprop;
}

struct bash 
{
    public bar mybar;
}

void Main()
{
    bash bash1 = new bash();
    bash1.mybar.myprop = 1;
    Console.WriteLine(bash1.mybar.myprop); //Outputs 1 (Direct access)

    bar bar2 = bash1.mybar;
    bar2.myprop = 2;
    Console.WriteLine(bash1.mybar.myprop); //Outputs 1 (Bug: access via a copy)

    ref bar bar3 = ref bash1.mybar;
    bar3.myprop = 3;
    Console.WriteLine(bash1.mybar.myprop); //Outputs 3 (Ref Local)

    bar3 = new bar();
    bar3.myprop = 4;
    Console.WriteLine(bash1.mybar.myprop); //Outputs 4 (Ref local with assignment)
}
like image 3
Brian Avatar answered Oct 17 '22 18:10

Brian


You can give yourself some syntactic sugar by implementing "shortcuts" that might get you closer to your goal.

public class ObjectOne
{
    public ObjectTwo ObjectTwo {get;set;}

    public VariableType Var {get{return ObjectTwo.Variable;}}
}

This allows you to write for example:

var one = new ObjectOne();

one.Var = something;

@Eric Lippert is right, this is only one possible solution the Question needs more information to be answered correctly.

like image 2
mxmissile Avatar answered Oct 17 '22 16:10

mxmissile