C#: Create and pass variable straight in the method call - c#

I would like to know how to declare new variable straight in the parameter brackets and pass it on like this:
MethodA(new int[]) //but how to fill the array if declared here? E.g. how to declare and set string?
MethodA(int[] Array)
...
and what if need to declare an object (class with constructor parameter)? Still possible within parameter list?

MethodA(new int[] { 1, 2, 3 }); // Gives an int array pre-populated with 1,2,3
or
MethodA(new int[3]); // Gives an int array with 3 positions
or
MethodA(new int[] {}); // Gives an empty int array
You can do the same with strings, objects, etc:
MethodB(new string[] { "Do", "Ray", "Me" });
MethodC(new object[] { object1, object2, object3 });
If you want to pass a string through to a method, this is how you do it:
MethodD("Some string");
or
string myString = "My string";
MethodD(myString);
UPDATE:
If you want to pass a class through to a method, you can do one of the following:
MethodE(new MyClass("Constructor Parameter"));
or
MyClass myClass = new MyClass("Constructor Parameter");
MethodE(myClass );

You can try this:
MethodA(new int[] { 1, 2, 3, 4, 5 });
This way you achieve the functionality you asked for.
There seems to be no way to declare a variable inside parameter list; however you can use some usual tricks like calling a method which creates and initializes the variable:
int[] prepareArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = i;
return arr;
}
...
MethodA(prepareArray(5));
...
With the strings, why not just use string literal:
MethodB("string value");
?

Either new int[0] or new int {} will work for you. You can also pass in values, as in new int {1, 2, 3}. Works for lists and other collections too.

In your case you would want to declare MethodB(string[] strArray) and call it as MethodB(new string[] {"str1", "str2", "str3" })
P.S.
I would recomment that you start with a C# tutorial, for example this one.

Do you simply mean:
MethodA("StringValue"); ??

As a side note: if you add the params keyword, you can simply specify multiple parameters and they will be wrapped into an array automatically:
void PrintNumbers(params int[] nums)
{
foreach (int num in nums) Console.WriteLine(num.ToString());
}
Which can then be called as:
PrintNumbers(1, 2, 3, 4); // Automatically creates an array.
PrintNumbers(new int[] { 1, 2, 3, 4 });
PrintNumbers(new int[4]);

Related

C# specify only second optional argument and use the default value for first [duplicate]

Is there a way to set up a C# function to accept any number of parameters? For example, could you set up a function such that the following all work -
x = AddUp(2, 3)
x = AddUp(5, 7, 8, 2)
x = AddUp(43, 545, 23, 656, 23, 64, 234, 44)
Use a parameter array with the params modifier:
public static int AddUp(params int[] values)
{
int sum = 0;
foreach (int value in values)
{
sum += value;
}
return sum;
}
If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:
public static int AddUp(int firstValue, params int[] values)
(Set sum to firstValue to start with in the implementation.)
Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:
int x = AddUp(4, 5, 6);
into something like:
int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);
You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.
C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.
1.You can make overload functions.
SomeF(strin s){}
SomeF(string s, string s2){}
SomeF(string s1, string s2, string s3){}
More info: http://csharpindepth.com/Articles/General/Overloading.aspx
2.or you may create one function with params
SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like
More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params
3.or you can use simple array
Main(string[] args){}

C# Why does the argument array has to be passed with the modifier ref if arrays are passed by reference?

I do not understand why this function was written like that:
System.Array.Resize<int>(ref int[], int)
If arrays are passed by reference by default
why wasn't it written like that:
System.Array.Resize<int>(int[], int)
This is because when we write a variable to a reference type object, there are kind of 2 parts, the actual object instance, and the reference which the variable name represents (32bit or 64bit memory address pointer internally, platform dependant). You can see that clearly with this sharplab.io snippet.
When we call a method, this pointer is copied, but the instance isn't, so:
var a = new Blah {Prop = "1"}; // Blah is a class, a reference type
Method(a);
void Method(Blah blah)
{
blah.Prop = "2"; // changes the shared instance, we know this.
blah = new Blah {Prop = "3"}; // has no effect.
}
Console.WriteLine(a.Prop); // 2
You see when we set blah inside of the method, we are mutating our local reference, not the shared one. Now if we use the ref keyword:
var a = new Blah {Prop = "1"};
Method(ref a);
void Method(ref Blah blah)
{
blah.Prop = "2"; // changes the shared instance, we know this.
blah = new Blah {Prop = "3"}; // now changes ref a outside
}
Console.WriteLine(a.Prop); // 3!
because the parameter blah is passed by reference, when we mutate it, we mutate the original reference a.
Arrays are indeed reference types, which means that changes done to the passed-in array object inside a method will be reflected on the caller's side:
public static void Foo(int[] a) {
a[0] = 1;
}
// ...
int[] a = new int[1];
Foo(a);
Console.WriteLine(a[0]); // 1
However, if you set the array to something else inside the method:
public static void Foo(int[] a) {
a = null;
}
// ...
int[] a = new int[1];
Foo(a);
Console.WriteLine(a[0]); // will not throw NRE
Declaring the parameter as ref will allow reassignments to the parameter to reflect on the caller's side.
Changing the size of the array requires creating a new array and hence re-assigning the parameter. You can't resize an array by mutating an existing array object somehow. This is why it needs to be declared as ref.
Simply speaking if your array is passed to a method as a ref parameter it can be replaced as a whole with another array created within the method.
It's not the case with arrays passed without ref keyword.
Code below illustrates the difference.
Note that individual elements of array parameters can be replaced in both cases (with of without ref keyword).
class Program
{
static void PrintArr(string comment, int[] arr)
{
Console.WriteLine($"{comment}:");
Console.WriteLine(string.Join(", ", arr.Select(e => e.ToString())));
}
static void NoRef(int[] arr)
{
int[] localArr = { 2, 4, 8, 10 };
arr = localArr;
}
static void ByRef(ref int[] arr)
{
int[] localArr = { 2, 4, 8, 10 };
arr = localArr;
}
static void Main()
{
int[] arr;
arr = new int[] { 1, 3, 4, 7, 9 };
PrintArr("Before NoRef is called", arr);
NoRef(arr);
PrintArr("After NoRef is called", arr);
PrintArr("Before ByRef is called", arr);
ByRef(ref arr);
PrintArr("After ByRef is called", arr);
Console.ReadLine();
}
}
}
Output for the code is shown below (note that ByRef method code replaced the array.
Before NoRef is called:
1, 3, 4, 7, 9
After NoRef is called:
1, 3, 4, 7, 9
Before ByRef is called:
1, 3, 4, 7, 9
After ByRef is called:
2, 4, 8, 10

C# params keyword accepting multiple arrays

Consider this method
public static void NumberList(params int[] numbers)
{
foreach (int list in numbers)
{
Console.WriteLine(list);
}
}
I can call this method and supply seperated single integers or just one array with several integers. Within the method scope they will be placed into an array called numbers (right?) where I can continue to manipulate them.
// Works fine
var arr = new int[] { 1, 2, 3};
NumberList(arr);
But if I want to call the method and supply it arrays instead, I get an error. How do you enable arrays for params?
// Results in error
var arr = new int[] { 1, 2, 3};
var arr2 = new int[] { 4, 5, 6 };
NumberList(arr, arr2);
The type you're requiring is an int[]. So you either need to pass a single int[], or pass in individual int parameters and let the compiler allocate the array for you. But what your method signature doesn't allow is multiple arrays.
If you want to pass multiple arrays, you can require your method to accept any form that allows multiple arrays to be passed:
void Main()
{
var arr = new[] { 1, 2, 3 };
NumberList(arr, arr);
}
public static void NumberList(params int[][] numbers)
{
foreach (var number in numbers.SelectMany(x => x))
{
Console.WriteLine(number);
}
}
public void Test()
{
int[] arr1 = {1};
int[] arr2 = {2};
int[] arr3 = {3};
Params(arr1);
Params(arr1, arr2);
Params(arr1, arr2, arr3);
}
public void Params(params int[][] arrs)
{
}
Your method is only set to accept a single array. You could use a List if you wanted to send more than one at a time.
private void myMethod(List<int[]> arrays){
arrays[0];
arrays[1];//etc
}
You cant by langauge means.
However there is a way to work arround this by overlading the method something like this:
public static void NumberList(params int[][] arrays)
{
foreach(var array in arrays)
NumberList(array);
}
See here

What is C# equivalent of TSQL's "IN" operator? What are the ways to check if X exists in X,Y,Z in c#?

What are the ways to check if X exists in X,Y,Z in c#?
For eg:
X=5;
I want to check if X's value matches any of the comma separated values..
if(x in (2,5,12,14)
new int[] { 2,5,12,14}.Contains(x);
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
list.Contains(5);
You may use .Contains method. e.g. listItems.Contains(x)
There is no in operator in C#, but you can implement an extension method to make the code more readable.
public static class Ext
{
public static bool In<T>(this T val, params T[] values) where T : struct
{
return values.Contains(val);
}
}
//usage: var exists = num.In(numbers);
Linq.Contains() what you searching for
// Create List with three elements.
var list = new List<string>();
list.Add("cat");
list.Add("dog");
list.Add("moth");
// Search for this element.
if (list.Contains("dog"))
{
Console.WriteLine("dog was found");
}
There are two methods Linq.Contains() method and an extension Linq.Contains<int>
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Use extension method.
var stp = new Stopwatch();
stp.Start();
bool a = list.Contains<int>(7);
stp.Stop();
Console.WriteLine("Time in extenstion method {0}", stp.Elapsed);
stp.Restart();
// Use instance method.
bool b = list.Contains(7);
stp.Stop();
Console.WriteLine("Time in normal method {0}", stp.Elapsed);
Performance benchmark : The version specific to List i.e, list.Contains(7); , found on the List type definition, is faster. I tested the same List with the two Contains methods.

Pass multiple optional parameters to a C# function

Is there a way to set up a C# function to accept any number of parameters? For example, could you set up a function such that the following all work -
x = AddUp(2, 3)
x = AddUp(5, 7, 8, 2)
x = AddUp(43, 545, 23, 656, 23, 64, 234, 44)
Use a parameter array with the params modifier:
public static int AddUp(params int[] values)
{
int sum = 0;
foreach (int value in values)
{
sum += value;
}
return sum;
}
If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:
public static int AddUp(int firstValue, params int[] values)
(Set sum to firstValue to start with in the implementation.)
Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:
int x = AddUp(4, 5, 6);
into something like:
int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);
You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.
C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.
1.You can make overload functions.
SomeF(strin s){}
SomeF(string s, string s2){}
SomeF(string s1, string s2, string s3){}
More info: http://csharpindepth.com/Articles/General/Overloading.aspx
2.or you may create one function with params
SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like
More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params
3.or you can use simple array
Main(string[] args){}

Categories

Resources