Sharon Watinsan
Sharon Watinsan

Reputation: 9850

C# getters and setters method definition - beginner

I am new to C#. i was going through a tutorial. and it shows how to create accesor-mutator to a variable as shown below;

public String var1 {

get {return "";}
set {someVar = value;}

} 

1.) Can't i create getters and setter like created in java

public getVar() {return "";}
public setVar(String x){var=x;}

2.) What is value used in C# ?

Upvotes: 4

Views: 7555

Answers (4)

Muhammad Babar
Muhammad Babar

Reputation: 8134

yes you can create getter setters as in java example

int marks;
public void setMarks(int marks)
{
this.marks=marks;
}
public int getMarks()
{
return marks;
}

Upvotes: 1

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Sure, you can do it like Java. But why? Property syntax allows a much better experience from the caller's point of view.

value is a pseudo-variable that you can use to set your internal variable with, etc. It's equivalent to x in your Java-like example.

Upvotes: 3

Servy
Servy

Reputation: 203816

  1. Sure you can. Properties in C# are designed to be syntactic sugar for just that. Under the hood a property is little more than a get/set method. It's just easier to create the two methods, it keeps the two methods in one place in the source code, it has simpler syntax for the caller, and properties that do nothing but just get/set a value are easier still to generate.

  2. It's a keyword. It is the value that is being passed into the method. If someone enters obj.var1 = "abc"; then value will be a reference to "abc".

Upvotes: 4

SLaks
SLaks

Reputation: 888167

  1. You can, but that's much more annoying to use, and ignores C# coding guidelines.

  2. value is the implicit parameter to the setter. It contains the value that the caller is setting the property to. (the right side of the Property = something call)

See the documentation.

Upvotes: 9

Related Questions