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.
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;
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.
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With