Skip to content

Instantly share code, notes, and snippets.

@anilkay
Last active May 21, 2024 22:17
Show Gist options
  • Select an option

  • Save anilkay/c1d63ef09369cd8cab0870d159b197d8 to your computer and use it in GitHub Desktop.

Select an option

Save anilkay/c1d63ef09369cd8cab0870d159b197d8 to your computer and use it in GitHub Desktop.
// See https://aka.ms/new-console-template for more information
bool result=Contains(new uint[] { 1, 2, 3, 4, 5 }, 3); // true
Console.WriteLine(result);
//Contains(new uint[] { 1, 2, 3, 4, 5 }, -6); // false
//Contains(new uint[] { 1, 2, -5, 4, 5 }, 6); // false
int[] arr=new int[] { 1, 6, 3, 4, 5 };
//int[] arr=new int[] { 1, -6, 3, 4, 5 }; // throw exception
//string []arr3= new string[] { "1", "2", "3", "4", "5" }; types are not numeric
//ConvertAllMethod<string,uint>(arr3); // throw exception
//bool []arr4= new bool[] { true, false, true, false, true };
//ConvertAllMethod<bool,uint>(arr4);
uint[] arr2=ConvertAllMethod<int,uint>(arr);
PrintArray(arr2);
result=Contains(arr2,2); // false
Console.WriteLine(result);
static bool Contains(uint[] arr, uint n)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == n)
{
return true;
}
}
return false;
}
// Print generic array
static void PrintArray<T>(T[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
//Convert All Method
static K?[] ConvertAllMethod<T,K>(T[] arr)
{
//Control Types are Numeric Types
if(!typeof(T).IsPrimitive || !typeof(K).IsPrimitive
|| Type.GetTypeCode(typeof(T))==TypeCode.String
|| Type.GetTypeCode(typeof(K))==TypeCode.String
|| Type.GetTypeCode(typeof(T))==TypeCode.Char
|| Type.GetTypeCode(typeof(K))==TypeCode.Char
|| Type.GetTypeCode(typeof(T))==TypeCode.Boolean
|| Type.GetTypeCode(typeof(K))==TypeCode.Boolean
)
{
throw new ArgumentException("Types are not numeric");
}
K?[] arrConverted=Array.ConvertAll(arr, x => {
try {
K? possibleUintValue=(K?)Convert.ChangeType(x, typeof(K));
if(possibleUintValue is null)
{
throw new ArgumentException("Array contains null value");
}
if(x is null)
{
throw new ArgumentException("Array contains null value");
}
if(Math.Abs((dynamic)possibleUintValue)!=Math.Abs((dynamic) x))
{
//Maybe never works.
throw new ArgumentException("Array contains negative value");
}
return possibleUintValue;
}
catch (OverflowException)
{
throw new ArgumentException("Array contains negative value");
}
});
return arrConverted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment