Here we will see three different advantages of @ symbol in C# application.
In front of C# keyword
We can use @ symbol in front of any keyword in C# and we can suppress general meaning of that keyword. For example, in below program we have used @ symbol in front of if and while, very known keyword of C# but using @ symbol we can use them as normal variable. To control if and while loop we have used if and while keyword simultaneously.
using System;
using System.Collections;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
int @if; // use if as an identifier and suppress it's general meaning
int @While = 0;
for (@if = 0; @if < 10; @if++)
Console.WriteLine("Value is " + @if);
while (@While < 10)
{
Console.WriteLine("Value is " + @While);
@While++;
}
Console.ReadLine();
}
}
}
using System.Collections;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
int @if; // use if as an identifier and suppress it's general meaning
int @While = 0;
for (@if = 0; @if < 10; @if++)
Console.WriteLine("Value is " + @if);
while (@While < 10)
{
Console.WriteLine("Value is " + @While);
@While++;
}
Console.ReadLine();
}
}
}
To preserve white space
We can preserve white space using @ symbol before long string. In below example we have declared a long string with lot of white space and newline character. As we have used @ symbol the string preserve its state as it is.
using System;
using System.Collections;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
String Name = @"Thsi
is
my
name
";
Console.WriteLine(Name);
Console.ReadLine();
}
}
}
using System.Collections;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
String Name = @"Thsi
is
my
name
";
Console.WriteLine(Name);
Console.ReadLine();
}
}
}
To insert special character within string
If we want to insert any special character within string then we have to use @ symbol in front of string. In below example we have declare a string which contents few special character like ‘and \ symbol. This is very useful to prevent SQL injection attack in application.
using System;
using System.Collections;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
String str = @"Thsi ' is \n complex string";
Console.WriteLine(str);
Console.ReadLine();
}
}
}
using System.Collections;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
String str = @"Thsi ' is \n complex string";
Console.WriteLine(str);
Console.ReadLine();
}
}
}
No comments:
Post a Comment