How to get the global variable inside the method - c#

class sample
{
public int i; //global variable
public int[] arr = new int[10];
public void fun(int i, int val)
{
Console.WriteLine(this.i); //I got Output is 11
arr[i] = val;
Console.WriteLine(arr[i]);
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
s.i = 1;
s.fun(1, 7);
Console.ReadLine();
}
}
How to get the global variable i inside the fun() method
Here the function variable name and global variable name are the same.

To access the field i within the fun() method, you can use the this keyword. For example:
class sample
{
public int i; //global variable
public int[] arr = new int[10];
public void fun(int i, int val)
{
this.i = i; // assign the value of the function parameter to the field
arr[i] = val;
Console.WriteLine(arr[i]);
}
}
Alternatively, you can also use a different name for the function parameter to avoid the naming conflict. For example:
class sample
{
public int i; // field
public int[] arr = new int[10];
public void fun(int j, int val)
{
i = j; // assign the value of the function parameter to the field
arr[j] = val;
Console.WriteLine(arr[j]);
}
}

Related

Cannot specify constructor arguments in declaration in C Sharp

This is the Question I am trying to solve in C Sharp.
I am getting an error:
Error Expected ; or = (cannot specify constructor arguments in declaration)
Can anyone help me to solve this or guide me to solve this?
namespace program
{
public class Integer
{
private int intvar;
public Integer()
{
intvar = 0;
}
public Integer(int x)
{
intvar = x;
}
public void display()
{
Console.Write(intvar);
Console.Write("\n");
}
public void add(Integer x, Integer y)
{
intvar = x.intvar + y.intvar;
}
}
class Program
{
static void Main(string[] args)
{
Integer a(5),b(45);
Integer c;
c.add(a,b);
c.display();
Console.ReadLine();
}
}
}
You cannot create objects like that in C#. Im assuming you come from C++ where this syntax is possible.
In C# you have to create objects using new:
Integer foo = new Integer(45);
To create a new instance of a type, you have to invoke one of the constructors of that type using the new operator. For example:
class Program
{
static void Main(string[] args)
{
var a = new Integer(5);
var b = new Integer(45);
var c = new Integer(); //result instance
c.add(a, b);
c.display();
Console.ReadLine();
}
}

How to count in anonymous method?

I have this an implementation of class IntList. I'm am supposed to: Use the capability of the anonymous methods to refer to a local variable in their enclosing method and the defined "Act"-method to compute the sum of an IntList’s elements (without writing any loops yourself). This is what I have done so far, but I doubt that it is correct. Any suggestions and explanations will help me here
What is my anonymous method's enclosing method in this case?
public delegate bool IntPredicate(int x);
public delegate void IntAction(int x);
class IntList : List<int>
{
public IntList(params int[] elements) : base(elements)
{
}
public void Act(IntAction f)
{
foreach(int i in this)
{
f(i);
}
}
public IntList Filter(IntPredicate p)
{
IntList res = new IntList();
foreach (int i in this)
{
if (p(i))
{
res.Add(i);
}
}
return res;
}
}
class Program
{
static void Main(string[] args)
{
// code here
IntList xs = new IntList();
// adding numbers, could be random. whatever really. Here just 0..29
for(int i =0; i<30; i++)
{
xs.Add(i);
}
int total = 0;
xs.Act(delegate (int x)
{
total = total + x;
Console.WriteLine(total);
}
);
Console.ReadKey();
}
}
I think this part is the "anonymous method" (because it is defined inline and doesn't have a method name):
delegate (int x)
{
total = total + x;
Console.WriteLine(total);
}
I think the "enclosing method" is Main().
I think the "local variable" is most likely total.
I ran your code and it seems correct to me.

Unable to Access Extension Method in Main Method

I am using extension method to convert string to integer. But i am not able to access extension method in main method. What was i did wrong. My Code is below
public static class ConvertIntExtensionMethod
{
public static int ConvertToInt(this int str) {
int value;
value = Convert.ToInt32(str);
return value;
}
}
static void Main(string[] args)
{
string str = "100";
//int i = 10;
//bool result = i.IsGreaterThan(100);
int result = str.ConvertIntExtensionMethod(); //Here is the problem
Console.WriteLine(result);
Console.ReadLine();
}
please try to help me thank you...
Extension methods must be defined in a top level static class, it seems that your ConvertIntExtensionMethod class is a nested class
If you want to add this method to string, the type of the param must be this string
Call str.ConvertToInt() instead of str.ConvertIntExtensionMethod()
str does not contain any member known as ConvertIntExtensionMethod(). You need to do this:
public static class ConvertIntExtensionMethod
{
public static int ConvertToInt(this string str)
{
int value;
value = Convert.ToInt32(str);
return value;
}
}
class Program
{
static void Main(string[] args)
{
string str = "5";
//int i = 10;
//bool result = i.IsGreaterThan(100);
int result = ConvertIntExtensionMethod.ConvertToInt(str); //Here is the problem
Console.WriteLine(result);
Console.ReadLine();
}
}
It will convert an integer as a string to an int.
I am give the wrong parameter type in the extension method. Main method passing string value but extension method parameter is integer. This is the problem what i found.
Updated code in Extension method is given below
public static int ConvertToInt(this string str)
{
int value;
value = Convert.ToInt32(str);
return value;
}

how can I change value of globally declared variable in c#

public int a;
public void currentvalue(int a)
{
if (a == 5)
{
a = 10;
Console.WriteLine("a" + a);
}
}
how can I change the value of a into 10
When you have both a global variable (field) and a local variable (parameter/local) with the same name in the same scope, the compiler will automatically choose the locally declared variable.
When dealing with a non-static (instance referenced) field, you can still access the field by using the this keyword. Example:
public class MyClass
{
public int number = 2;
public void Calc(int number) //when number: 4
{
int result1 = number * 3; //result1: 12
int result2 = this.number * 3; //result2: 6
}
}
If your globally declared variable is static, you can't use this (which is only usable on instance references). In that case, use a type reference instead:
public class MyClass
{
public static int number = 2;
public void Calc(int number) //when number: 4
{
int result1 = number * 3; //result1: 12
int result2 = MyClass.number * 3; //result2: 6
}
}
You may want to read up on the this keyword here.
You can use ref keyword and pass the reference into function :
public void currentvalue(ref int a)
{
if (a == 5)
{
a = 10;
Console.WriteLine("a" + a);
}
}

How to dynamically create a List in a function in C#

I have a code written in c. I have a pointer to int in main and I pass it to a function. This function allocates memory and populates the array, then it returns. Basically looks like this:
main()
{
int* array;
function(&array);
}
void function(int** array)
{
int size = 25;
*array = malloc(size);
(*array)[0] = 42;
}
Size is not known in main. How do I do this in C#? I tried with List but I cannot make it work. I have tried both List and ref List, and they both give Index was out of range.
EDIT:
This works fine
class Program
{
static void function(List<int> array)
{
array.Add(42);
}
static void Main(string[] args)
{
List<int> array = new List<int>();
function(array);
}
}
And this one too
class Program
{
static void function(out int[] array)
{
array = new int[25];
array[0] = 42;
}
static void Main(string[] args)
{
int[] array;
function(out array);
}
}
But the following throws an exception
class Program
{
static void function(out List<int> array)
{
array = new List<int>(25);
array[0] = 42;
}
static void Main(string[] args)
{
List<int> array;
function(out array);
}
}
Class Demo
{
static void main (string[] args)
{
var result=Add();
Console.WriteLine(result[0]);
}
static List<int> Add ()
{
var listOfints= new List<int>();
listOfints.Add(42); //either this or declare an array of integers and get it initialized by reading the user value and pass the same as param here to initialize and return the array
return listOfints;
}
}
c# has the ref keyword for this purpose. Although it is not required in this case because an array is a reference type anyway it is a good idea nevertheless because it conveys the design intent. Better yet to use the out keyword as the argument to the function doesn't need to be initialized before the call.
Try this:
class Program
{
static void Main(string[] args)
{
int[] a;
function(out a);
Debug.WriteLine(a.Length);
}
public static void function(out int[] array)
{
array=new int[25];
array[0]=42;
}
}
Edit 1 - Alternate way with returning an array
class Program
{
static void Main(string[] args)
{
int[] a = CreateArray();
Debug.WriteLine(a.Length);
}
public static int[] CreateArray()
{
int[] array=new int[25];
array[0]=42;
return array;
}
}
Edit 2 - Example with two out parameters
class Program
{
static void Main(string[] args)
{
int[] akw, zuk;
function(out akw, out zuk);
Debug.WriteLine(akw.Length);
Debug.WriteLine(zuk.Length);
}
public static void function(out int[] A, out int[] B)
{
A=new int[25];
B=new int[15];
A[0]=42;
B[0]=21;
}
}
I think the reason that you're having problems assigning value [0] to a c# list is that unless you create a List<> collection with a predefined start size it will be empty. Thus entry [0] is null and can't be set.
If you want to directly access element 0, use this:
void function(out List<int> list)
{
list = new List<int>(25);
list[0] = 42;
}
If instead you don't need to / know the initial allocation size of the List, use this: (recommended IMHO)
void function(out List<int> list)
{
list = new List<int>();
list.Add(42);
}
Good luck!
Another way (Although it's recommended to use a List<int>)
Replace int * with out int[]
public class Program
{
public static void Main()
{
int[] array;
function(out array);
Console.WriteLine(array[0]);
}
static void function(out int[] array)
{
int size = 25;
array = new int[size];
array[0] = 42;
}
}
Output
42
As mentioned above c# uses references. Pointers are supported but you would need to write unmanaged code.. More info about references here
https://msdn.microsoft.com/en-us/library/14akc2c7.aspx
A sample is below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace alistnamespace
{
class Program
{
static void Main(string[] args)
{
List<int> my_list=new List<int>();
functionaddtolist(ref my_list);
for(int i=0;i<my_list.Count;i++)
{
Console.WriteLine("List item " + i.ToString() + "=" + my_list[i]);
}
}
static void functionaddtolist(ref List<int> mylist_ref)
{
mylist_ref.Add(42); //Add one element
}
}
}

Categories