C# : Partial class , Indexers, Optional parameters for methods : Part 26
- It allows us to split class into 2 or more files. All these partial classes are than combined to form single class when application is compiled.
- Spreading class over multiple files as partial class allows multiple programmers to work on it simultaneously.
Indexers
- Default index provided by .net is called indexers, It can be int or string.
- Indexers are generally used in list, arrays, dictionary's, etc.
Optional parameters for method
- Parameter arrays : Refer following e.g.
namespace OptionalParameter
{
class Program
{
static void Main(string[] args)
{
var MyResult = AddNumbers(new int[] { 2, 8, 9 });
}
public static int AddNumbers(params int[] Num)
{
int result = 0;
foreach (int item in Num)
{
result = result + item;
}
return result;
}
}
}
namespace OptionalParameter
{
class Program
{
static void Main(string[] args)
{
var MyResult = AddNumbers(4, 67);
}
public static int AddNumbers(int a, int b)
{
return a + b;
}
public static int AddNumbers(params int[] Num)
{
int result = 0;
foreach (int item in Num)
{
result = result + item;
}
return result;
}
}
}
namespace OptionalParameter
{
class Program
{
static void Main(string[] args)
{
var MyResult = AddNumbers(4, 67);
}
public static int AddNumbers(int a, int b, int[] Num = null)
{
int result = 0;
result = a + b;
if (Num != null)
{
foreach (int item in Num)
{
result = result + item;
}
}
return result;
}
}
}
namespace OptionalParameter
{
class Program
{
static void Main(string[] args)
{
var MyResult = AddNumbers(2);
}
public static int AddNumbers(int a, int b = 6, int c = 30)
{
return a + b + c;
}
}
}
namespace OptionalParameter
{
class Program
{
static void Main(string[] args)
{
var MyResult = AddNumbers(4, 67);
}
public static int AddNumbers(int a, int b, [Optional]int[] Num)
{
int result = 0;
result = a + b;
if (Num != null)
{
foreach (int item in Num)
{
result = result + item;
}
}
return result;
}
}
}
No comments