1

I've just started learning C#. A common issue I have is when I am working with an object instance and want to access/assign multiple fields then I have to call the object name each time. I come from a background in Delphi and I was wondering if C# has something similar to with..do block.

For example. Let's say I had School Class with fields Name and Address

In Delphi, I could do the following

mySchool = School.new();
with mySchool do
begin
 Name := 'School Name';
 Address := 'School Address';
end

The compiler would understand that Name and Address are being called on the mySchool object.

Whereas in C# I have to do the following

mySchool = new School();
mySchool.Name = "School Name";
mySchool.Address = "School Address";

I was just wondering if there is a language construct similar to the Delphi one above that would eliminate the need for me to type out the object name repeatedly.

I know in this example is rather trivial and I should rather use a parameterized constructor but my question is for times when I am doing a multitude of things with the same object and having such a language construct would save me quite a bit of typing.

Also, I'm vaguely aware of namespacing although, my understanding is that you can't use an object/variable as a namespace. Please correct me if I'm wrong.

  • You create the class, on the constructor you specify may the passed arguments on the brackets be instantiated as attrs. I'm not super savy on c# since i hate microsoft and i only use C# for unity, but since its quite similar to python/java etc it shall be something similar to this class School(Name, Address){ #unsure if you require to call a constructor method or this is sufficient** str Name = this.Name; str Address = this.Address; return School #you may not need to return the class object mySchool = new School("Hogwarts", "Somewhere Lane") – Mr-Programs Aug 31 '18 at 13:59

2 Answers2

1

You could use an object initializer in this case:

var mySchool = new School
{
    Name = "School Name",
    Address = "School Address"
};
rory.ap
  • 34,009
  • 10
  • 83
  • 174
0

I think that the selected answer doesn't give you what you asked for.

By using object initializer, you will still have to manually type properties' names every time.

A constructor is what you're looking for:

class Program
{
    static void Main(string[] args)
    {
        School school1 = new School("School Name", "School Address");
    }
}

public class School
{
    public string Name { get; set; }
    public string Address { get; set; }

    public School(string name, string address)
    {
        this.Name = name;
        this.Address = address;
    }
}
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32