using System;
public static class SwapTwoIntegers
{
private static void Main()
{
var a = 55;
var b = 69;
SwapInts(ref a, ref b);
Console.WriteLine(a); // 69
Console.WriteLine(b); // 55
}
private static void SwapInts(ref int a, ref int b)
{
a ^= b;
b ^= a;
a ^= b;
}
}
Category: C# Snippets
How to calculate factorial with single line of code in C#
using System;
using System.Linq;
using System.Numerics;
public static class Factorial
{
public static void Main(string[] args)
{
int num = 100;
Console.WriteLine(Enumerable.Range(1, num).Select(i => new BigInteger(i)).Aggregate((a, b) => a * b));
}
}
// 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
How to convert decimal number to hexadecimal in C# using method
using System;
using System.Text;
class DecToHex
{
static void Main(string[] args)
{
long num = 100000;
Console.WriteLine(DecimalToHex(num)); // 186A0
}
private static string DecimalToHex(long num)
{
var res = new StringBuilder();
while (num > 0)
{
var reminder = num % 16;
if (reminder > 9)
{
res.Insert(0, (char)(reminder + 55));
}
else
{
res.Insert(0, reminder);
}
num /= 16;
}
return res.ToString();
}
}
How to convert decimal to binary number in C# using method
using System;
using System.Text;
class DecToBin
{
static void Main(string[] args)
{
long num = int.MaxValue * 2L;
Console.WriteLine(DecimalToBinary(num)); // 11111111111111111111111111111110
}
private static string DecimalToBinary(long num)
{
StringBuilder res = new StringBuilder();
while (num > 0)
{
res.Insert(0, num % 2);
num /= 2;
}
return res.ToString();
}
}
How to convert binary number to decimal in C# using method.
using System;
class BinToDec
{
static void Main(string[] args)
{
string binary = "101";
Console.WriteLine(BinaryToDecimal(binary)); // will return 5
}
private static long BinaryToDecimal(string binary)
{
long decimalNum = 0;
for (int i = binary.Length - 1, pow = 0; i >= 0; i--, pow++)
{
decimalNum += int.Parse(binary[i].ToString()) * (long)Math.Pow(2, pow);
}
return decimalNum;
}
}
Reverse string with single line of C# code.
using System;
using System.Linq;
static class ReverseString
{
public static void Main()
{
string text = "!uoy htiw eb ecrof eht yaM";
Console.WriteLine(string.Join("", text.Reverse()));
}
}
Replace multiply whitespaces with single space inside text using C#.
using System;
using System.Text.RegularExpressions;
static class ReplaceWhiteSpaces
{
public static void Main()
{
string text = "This is some text with whitespaces in it . : )";
Console.WriteLine(Regex.Replace(text, @"(\s)\1+", " "));
}
}
Easy way to find all palindromes inside string array using C#.
using System;
using System.Linq;
static class Palindromes
{
private static void Main()
{
string[] words = { "test", "notPalindrome", "azuruza", "aha", "what?", "b" };
Console.WriteLine(string.Join(", ", words.Where(w => w.SequenceEqual(w.Reverse()))));
}
}