Java static statements in C# [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is a Java static block equivalent to a C# static constructor?
Is there an equivalent to:
public class people {
private static int x;
//...
static {
x = 3;
}
}
of JAVA in C#.NET?

Yeah, it looks mostly the same
public class People
{
private static int x;
static People()
{
x = 3;
}
}
but you could also do this:
public class People
{
private static int x = 3;
}

you can use a static constructor
static people()
{
x= 3;
}
see http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx
or you can just initialise it as-is
private static int x = 3;

Related

An object reference is required for the non-static field, method, or property 'Program.x' [duplicate]

This question already has answers here:
Compiler Error CS0120 [duplicate]
(2 answers)
Closed 2 months ago.
I am new to C#, sorry if this is duplicate. I am simply trying to add two variables together but I get the error from the title
An object reference is required for the non-static field, method, or property 'Program.x'
Here is code
using System;
namespace HelloWorld
{
class Program
{
int x = 3;
int y = 10;
static void Main(string[] args)
{
int mathResults = x + y;
string results = mathResults.ToString();
Console.WriteLine("Hello World!");
}
}
}
Could someone please explain WHY I am getting this error? Thank you!
As your Main() method is static, you must use static variables in it.
So it should be like this :
class Program
{
static int x = 3;
static int y = 10;
static void Main(string[] args)
{
int mathResults = x + y;
string results = mathResults.ToString();
Console.WriteLine("Hello World!");
}
}

How C# Method change the value of the parameter [duplicate]

This question already has answers here:
c# pass by value
(3 answers)
Closed 2 years ago.
I am confused about how the code below works.
Why is the output not 10 but 5?
public class Program
{
public void MyFunc(int x){
x = 10;
}
public void Main()
{
int x = 5;
MyFunc(x);
Console.WriteLine(x);
}
}
Thanks a lot.
Read about the "ref keyword"
Now result is 10
public static void MyFunc(ref int x)
{
x = 10;
}
public static void Main()
{
int x = 5;
MyFunc(ref x);
Console.WriteLine(x);
}

Assigning to a variable by reference?

Thanks to the kind folks who answered my previous question from a few days ago, I now know how to pass arguments by reference:
static void Main()
{
int i = 0;
Add(ref i, 100);
// now i == 100
}
static void Add(ref int arg, int increment)
{
arg += increment;
}
But is there a way for me not to just pass i by reference, but actually store its location in another variable? By that I mean use i like I did in my example; affecting the original instance, but in a way that's permanently linked and not leaving scope.
I vaguely know that I could use a pointer to determine the location in unsafe context but I was wondering if I could do this without any of that, or if it is just recommended to use the unsafe method.
If you are using C# 7 you can use ref local and ref return to store an updateable reference to any field.
In this example I change the private field _privateField from 0 to 100 from outside Foo, the class in which it is defined, by returning it as a ref int and updating it by reference.
class Foo
{
private int _privateField = 0;
public ref int GetReference()
{
return ref _privateField;
}
public override string ToString()
{
return _privateField.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField = 100;
Console.WriteLine(foo);
}
}
Prior to that, you'd have to store the value in a field contained in an object, and pass around a reference to the object instead.
In this example I change the value from 0 to 100 from outside Foo, even though it is stored (indirectly) in a field that is private inside the Foo instance.
class ValueTypeReference<T> where T : struct
{
public T Value { get; set; }
}
class Foo
{
private ValueTypeReference<int> _privateField = new ValueTypeReference<int>{ Value = 0 };
public ValueTypeReference<int> GetReference()
{
return _privateField;
}
public override string ToString()
{
return _privateField.Value.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField.Value = 100;
Console.WriteLine(foo);
}
}
Output:
100
Well, if I udnerstood you correctly, you want the variable to have global scope, which can be achieved by putting variable as class field/property:
class Program
{
private static int _i;
static void Main()
{
_i = 0;
Add(100);
// now _i == 100
}
static void Add(int increment)
{
_i += 100;
}
}

Methods not working? [duplicate]

This question already has an answer here:
C# - Why is this variable not being changed after being put through a method [duplicate]
(1 answer)
Closed 5 years ago.
Here is the block of code that I am having a bit of trouble with:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public void MultiplyByTen(int num) {
num *= 10;
}
}
}
When I run this block of code, I got 10 as the output instead of 100. My question is: Why does this happen and how to solve it?
Thanks for the help.
The problem is that when the variable number enters into the method MultiplyByTen the value is copied and the variable you are modifying inside it's in fact the copy, so, the original was not changed.
Try this instead:
public static void MultiplyByTen(ref int num)
{
num *= 10;
}
But remember you will have to call it with the ref keyword as well.
static void Main()
{
int number = 10;
MultiplyByTen(ref number);//Notice the ref keyword here
Console.WriteLine(number);
Console.ReadKey(true);
}
I recommend you to also check this out: Passing Objects By Reference or Value in C#
You need to return the value back to the function also assign the returned value to the number.
static void Main()
{
int number = 10;
number = MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public int MultiplyByTen(int num)
{
return num *= 10;
}
Using your implementation:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
//MultiplyByTen(number);
//Console.WriteLine(number);
Console.WriteLine(MultiplyByTen(number));
Console.ReadKey(true);
}
static public int MultiplyByTen(int num) {
return num *= 10;
}
}
}

What is the purpose of delegates and what are their advantages? [duplicate]

This question already has answers here:
When & why to use delegates? [duplicate]
(8 answers)
Closed 7 years ago.
Can anybody explain to me why we need delegates and what are the advantages of them?
Here is a simple program I have created with and without delegates (using plain methods):
Program with without delegates:
namespace Delegates
{
class Program
{
static void Main(string[] args)
{
abc obj = new abc();
int a = obj.ss1(1, 2);
int b = obj.ss(3,4);
Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
Console.ReadKey();
}
}
class abc
{
public int ss(int i, int j)
{
return i * j;
}
public int ss1(int x, int y)
{
return x + y;
}
}
}
Program with Delegates:
namespace Delegates
{
public delegate int my_delegate(int a, int b);
class Program
{
static void Main(string[] args)
{
my_delegate del = new my_delegate(abc.ss);
abc obj = new abc();
my_delegate del1 = new my_delegate(obj.ss1);
int a = del(4, 2);
int b = del1(4, 2);
Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
Console.ReadKey();
}
}
class abc
{
public int ss(int i, int j)
{
return i * j;
}
public int ss1(int x, int y)
{
return x + y;
}
}
}
Both programs give the same results, so what is advantage of using Delegates?
Thanks.
Delegate is designed to program in event-driven approach which creates a more decoupled source code.
With delegates, we can create something like publisher-subscriber pattern where subscribers can register to receive events from publishers.
We usually see delegates in use as event handlers. For example, with delegates we can create reusable controls by dispatching an event when something happens (e.x: click event,...), in this case, the control is the publisher, any code (subscriber) interested in handling this event will register a handler with the control.
That's one of the main benefits of delegates.
There are more usages pointed out by #LzyPanda in this post: When would you use delegates in C#?

Categories

Resources