.Net C# Language Basic

26. October 2008 10:31

.Net Working With Numbers C#

int i = 0;
// convert from a string
int i = int.Parse("1");
// convert froma string and don’t throw exceptions
if (int.TryParse("1", out i)) {}
i++;
// increment by one
i--; // decrement by one
i += 10; // add 10
i -= 10; // subtract 10
i *= 10; // multiply by 10
i /= 10; // divide by 10
i = checked(i*2) // check for overfl owerflow
i = unchecked(i*2) // ignore overfl owerflow

.Net Dates and Times C#

DateTime now = DateTime.Now; // date and time
DateTime today = DateTime.Today; // just the date
DateTime tomorrow = today.AddDays(1);
DateTime yesterday = today.AddDays(-1);
TimeSpan time = tomorrow - today;
int days = time.Days;
int hours = time.Hours;
int minutes = time.Minutes;
int seconds = time.Seconds;
int milliseconds = time.Milliseconds;
time += new TimeSpan(days, hours, minutes, seconds,
milliseconds);

.Net Conditional Logic C#

if (i == 0) {}
if (i <= 10) {} else {}
switch (i) { 
    case 0:
    case 1: 
        break;
    case 2:
        break;
    default: 
        break;
}

.Net Compare Operators C#

if (i == 0) // equal
if (i != 0) // not equal
if (i <= 0) // less than or equal
if (i >= 0) // greater than or equal
if (i > 0) // greater than
if (i < 0) // less than
if (o is MyClass) // check type of object
if (o == null) // check if reference is null

.Net Loops C#

for (int i=0; i<10; i++) {}
while (i<10) { i++; }
do { i++; } while (i<10);
foreach (ListItem item in list.Items) {}

.Net Define New Types C#

struct MyValueType {} // defi nes a value type
class MyClass { // defi nes a reference type
    // fields
    const string constName = "DotNetExplorer.com";
    static string staticName = "DotNetExplorer.com";
    readonly string readOnlyName;
    string instName;
    // properties
    public string Name
    {
// read/write
        get { return instName; }
        set { instName = value; }
    }
    public string ReadOnlyName { get { return instName; } }
    // methods
    public void Print() { Console.WriteLine(instName); }
    public int Add(int a, int b) { return a + b; }
    public static void PrintStatic() {
    Console.WriteLine(staticName); }
    // constructors
    public MyClass() {} // default constructor
    public MyClass(string name)
    {
        readOnlyName = name;
        instName = name;
   
}
}

.Net Inheritance C#

class MyClass : Object {
    // override inherited method
    public override string ToString() {
        // call base class version
        string s = base.ToString();
        return "Hello " + s;
    }
}

.Net Working with XML C#

using System.Xml;
using System.IO;

// Create an XML fi le
using (XmlWriter xw = XmlWriter.Create(@"c:\names.xml"))
{
    xw.WriteRaw(
"<names>");
    xw.WriteRaw(
"<name>Tom</name>");
    xw.WriteRaw(
"<name>Daniel</name>");
    xw.WriteRaw(
"</names>");
}

// Load an XML fi le
XmlDocument doc = new XmlDocument();
doc.Load(
@"c:\names.xml");
foreach (XmlNode node in doc.SelectNodes("//name/text()"))
{
Console.WriteLine(node.Value);
}

.Net Working With Text C#

using System.Text;
using System.IO;

string name = "Daniel";
string hello1 = "Hello " + name;
string hello2 = string.Format("Hello {0}", name);
Console.WriteLine("Hello {0}", name);
StringBuilder sb = new StringBuilder("Hello ");
sb.AppendLine(name);
sb.AppendFormat(
"Goodbye {0}", name);
Console.WriteLine(sb.ToString());

// Create a text file
using (StreamWriter w = File.CreateText(@"c:\names.txt")) {
    w.WriteLine(
"Tom");
    w.WriteLine(
"Daniel");
}

// Read from a text file
using (StreamReader r = File.OpenText(@"c:\names.txt")) {
    while (!r.EndOfStream) {
        Console.WriteLine(r.ReadLine());
    }
}
foreach (string s in File.ReadAllLines(@"c:\names.txt")) {
    Console.WriteLine(s);
}

.Net Working With a Database C#

using System.Data;
using System.Data.SqlClient;

string cs = @"Data Source=.\SQLEXPRESS;" +
string cs = @"Initial Catalog=NamesDB;" +
string cs = @"Integrated Security=True;";
using (SqlConnection con = new SqlConnection(cs)) {
    con.Open();
    string sql = "INSERT INTO Names(Name) VALUES(@Name)";
    // insert a record
    SqlCommand cmd1 = new SqlCommand(sql, con);
    cmd1.Parameters.Add(
"@Name", SqlDbType.NVarChar, 100);
    cmd1.Parameters[
"@Name"].Value = "Bob";
    cmd1.ExecuteNonQuery();
    // insert a second record
    cmd1.Parameters["@Name"].Value = "David";
    cmd1.ExecuteNonQuery();
    // read records
    sql = "SELECT * FROM Names";
    SqlCommand cmd2 = new SqlCommand(sql, con);
    using (SqlDataReader r = cmd2.ExecuteReader()) {
        int iName = r.GetOrdinal("Name");
        while (r.Read()) {
            Console.WriteLine(
                r.IsDBNull(iName)?
"Null":r.GetString(iName)
            );
        }
    }
    // read a single value
    sql = "SELECT TOP 1 Name FROM Names";
    SqlCommand cmd3 = new SqlCommand(sql, con);
    Console.WriteLine(cmd3.ExecuteScalar());
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

.Net | .Net C#



Powered by BlogEngine.NET 1.4.5.0