Implicitly type local variable
Local variables of the implied type are declared with the Var keyword, as follows:
var i = 123;
var h=123.123;
var s = “oec2003";
var intArr = new[] {1,2,3,4} ;
var a = new[] { 1, 10, 100, 1000 };
At first glance it's a bit like the declarative way in JavaScript, though the keyword is essentially the same.
After a variable declared with the var keyword in c#3.0 is assigned, the compiler automatically infers the type of the variable at compile time based on the type of the variable value. So it's still a strong type, this is different from object. In fact, the VAR keyword is not a specific type, but only plays a role in the placeholder, after compiling will be replaced by the appropriate type. It is important to note that variables declared with VAR must be assigned an initial value, otherwise a compilation error occurs because the type of the variable cannot be inferred from the value without assignment.
VAR can only declare local variables and can be used in foreach, such as:
var nums=new []{1,2,3,4,5};
foreach(var i in nums)
{
}
Extension methods
This is a very useful feature, and the extension method allows us to add an instance method of an existing type without changing the source code. The class in which the extension method resides must be a static class. As follows:
public static class oec2003Extensions
{
public static bool IsValidEmail(this String s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}
The above IsValidEmail static method is in the static class Oec2003extensions class, which can be used in any namespace, where the namespace is referenced.
The purpose of the IsValidEmail method is to validate e-mail messages. There are three parameters in the method: this String S. This is just a compilation requirement, as a hint to tell the compiler that this method is likely to be used as an extension method; string is the type we need to extend; S is the content of the message to be validated. Let's look at how to use this extension method.
protected void Button2_Click(object sender, EventArgs e)
{
if (this.TextBox1.Text.Trim().IsValidEmail())
{
Response.Write("email is right");
}
else
{
Response.Write("email is error");
}
}
Is it amazing that there is more than one IsValidEmail method just added in string type, which can be invoked directly to verify the email address.