Posts

Showing posts with the label Generics

Donate

Generic Method With BitConverter.GetBytes() Throws Error: CS1503 Argument 1: cannot convert from 'T' to 'bool'

Image
Hello And Good Day! There was a post in VBForums Generic Method with BitConverter.GetBytes problem on how to pass a T variable without causing the issue CS1503 Argument 1: cannot convert from 'T' to 'bool' private static byte [] GetBytes<T> (T valu) { var bytes = BitConverter.GetBytes(valu); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); return bytes; } Since Generic Constraints for a numeric types isn't available at this time, I attempted to solve this issue by checking the type of T and then perform the conversion explicity. private static byte [] GetBytes<T>(T value ) { byte [] bytes; ushort val1; uint val2; Type t = typeof (T); if (t == typeof ( ushort )) { val1 = Convert.ToUInt16( value ); bytes = BitConverter.GetBytes(val1); } else if (t == t

Match Item That Exists In A List Using Regular Expression And LINQ

Hi! Using Any() in LINQ, we can match/find an item that exists in a List<T> or IEnumerable using Regular Expressions. if (Products.Any(t => Regex.IsMatch(t, ProductsFromFrance.FrenchProdPattern)) { //true statement here.. } Where Products is the List object and ProductsFromFrance.FrenchProdPattern is the Regular Expression pattern.

Example Of IsPalindrome Generic Function Using Queue In C#

Hello, Excerpt from .NET 4.0 Generic's Guide , there's an example on testing whether a string is Palindrome using a Stack<T> object. I decided to create a a Queue<T> based method. One additional tip was to reverse the Queue object. See sample function below: public static bool IsPalindromic<T>(IEnumerable<T> inputSequence) where T : IComparable { Queue<T> buffer = new Queue<T>(); foreach (T element in inputSequence) { buffer.Enqueue(element); } buffer = new Queue<T>(buffer.Reverse()); for ( int i = 0; i < inputSequence.Count(); i++) { if (buffer.Dequeue().CompareTo(inputSequence.ElementAt(i)) == 0) { continue ; } else return false ; } return true ; } Source Code: Example Of IsPalindrome Generic Function Using Queue In C# That

Donate