Normally we write FOR loop logic to reverse a string, may be because we dont explore the in-built functions of the language.
char [] strArray = TextBox1.Text.ToCharArray();
Array.Reverse( strArray );
string ReverseString = new string( strArray );
Label1.Text = ReverseString;
Wednesday, December 31, 2008
Reverse String in C#
Friday, November 21, 2008
Differences Between Properties and Indexers in C#
Properties:
1)Identified by its name.
2)Accessed through a simple name or a member access.
3)Can be a static or an instance member.
4)A get accessor of a property has no parameters.
5)A set accessor of a property contains the implicit value parameter.
Indexers:
1)Identified by its signature.
2)Accessed through an element access.
3)Must be an instance member.
4)A get accessor of an indexer has the same formal parameter list as the indexer.
5)A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.
Clear all Textboxes
In Our applications in most of the cases we have to clear all text boxes (when Cancel or Reset button is clicked)
This code is to clear all text boxes in the form .
Use This code in Button click event
public void imgcancel_Click(object sender, ImageClickEventArgs e) {
FindControl(Form.Controls);
}
'Find Control Method Definition
public static void FindControl(ControlCollection ChildCtrls)
{
foreach (Control Ctrl in ChildCtrls)
{
if (Ctrl is TextBox)
((TextBox)Ctrl).Text = "";
else
FindControl(Ctrl.Controls);
}
}
Friday, August 1, 2008
My New Rank in C-Sharpcorner
In June, I spent most of the time in SQL Server Central community by posting answers because of that i was in TOP 5 in Montly TOP contributors. This was a great experience. Now In July, I spent most of the time in C-Sharpcorner, by posting answers to mainly C#, ASP.Net questions and other .Net Related questions.
As always Hard work pays, I am the MOST VALUABLE CONTRIBUTOR (MVC) in C# Corner. This is one more milestone in my Career.....
Friday, July 4, 2008
Method Overloading
In complex applications written in C#, we may need many methods which do essentially similar functions but are just different enough to be considered unique. For example, we may have to calculate a person's tax liability and would need to implement a method for doing this calculation in our application program. However, there are many different rules when it comes to tax calculations and they vary throughout the world. While there may be many rules, one basic equation stays the same: Your net income equals your gross income minus a computed tax amount. It is the method of computing your tax that varies.
We would probably have to implement different methods for each type of tax calculation. And, we could give each method a unique name such as TaxCalc1, TaxCalc2, TaxCalc3, etc. But wouldn't it be nice to just name the method TaxCalc and pass different arguments to it based on the computation desired?
For instance, let's say you live in a region within your country where you are taxed on your personal income, the value of your home, and any income you generate by doing business. On sales you generate through business activity, you must pay a gross receipts tax on all sales. If you own your home, you must pay a property tax on the imputed value of it. Then lastly, you must pay a tax on all income you generate through a job with another employer.
Check out the below link
http://www.codersource.net/csharp_method_overloading_ed.html
OOPS Concepts Part 1
To day i woule like to take a step back and give some information on OOPS concepts.
What Is an Object?
An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.
What Is a Class?
A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.
What Is Inheritance?
Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.
What Is an Interface?
An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it.
Keep watching.....
Thursday, June 26, 2008
Override ToString method
This C# code snippet overrides the ToString method inherited from System.Object in order to display the private variables.
public class MyClass
{
private string customer ="";
private int customerID = 0;
public string Customer
{
get { return customer; }
set { customer = value; }
}
public int CustomerID
{
get { return customerID; }
set { customerID = value; }
}
public override string ToString()
{
return string.Format ("Customer = {0} ID = {1}", Customer, CustomerID);
}
}
Tuesday, June 24, 2008
Sort Array
This C# code snippet sorts the elements of an array into ascending order
public class ReverseArraySort
{
public static void Main()
{
string[] strings = {"beta", "alpha", "gamma"};
Console.WriteLine ("Array elements: ");
DisplayArray (strings);
Array.Sort (strings); // Sort elements
DisplayArray (strings);
}
public static void DisplayArray (Array array)
{
foreach (object o in array)
{
Console.Write ("{0} ", o);
}
Console.WriteLine();
}
}
Thursday, June 19, 2008
Retrieve Current Screen Resolution
Gets the dimensions, in pixels, of the current video mode of the primary display
MessageBox.Show( "Monitor Size:" + SystemInformation.PrimaryMonitorSize );
Thursday, June 12, 2008
Call with variable arguments
Sometimes we may require a variable number of arguments to be passed to a function. For example we may require a sum function which calculates the total of the numbers passed to it no matter how many numbers are passed.
In C# we can use the Params keyword and pass variable no of arguments to a function. It's much like using ParamArray in VisualBasic language. The syntax of params arguments is:
params datatype[] argument name
static void ListArguments (params object[] arguments)
{
foreach (object argument in arguments)
{
Console.WriteLine (argument);
}
}
public static void Main( )
{
ListArguments ("Arguments: ", DateTime.Now, 3.14f);
}
Saturday, June 7, 2008
IS vs AS
Use the as operator when the normal program flow is to test for the interface and—immediately—cast the object for access to the interface members.
Use the is operator when the normal program flow is to test for the interface; but, interface member access is either delayed or does not occur at all.
Calculate Fibonacci number
static int Fibonacci (int x)
{
Console.WriteLine ("x = {0}", x);
if (x <= 1)
{
return 1;
}
return Fibonacci (x-1) + Fibonacci (x-2);
}
static void Main( )
{
Console.WriteLine ("Fibonacci no. = {0}", Fibonacci (5));
Console.ReadKey();
}
Monday, June 2, 2008
Write a Registry key
using Microsoft.Win32;
...
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey
("SOFTWARE\\Test\\Preferences");
if (masterKey == null)
{
Console.WriteLine ("Null Masterkey!");
}
else
{
try
{
masterKey.SetValue ("MyKey", "MyValue");
}
catch (Exception ex)
{
Console.WriteLine (ex.Message);
}
finally
{
masterKey.Close();
}
}
Read a Registry key
using Microsoft.Win32;
...
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey
("SOFTWARE\\Test\\Preferences");
if (masterKey == null)
{
Console.WriteLine ("Null Masterkey!");
}
else
{
Console.WriteLine ("MyKey = {0}", masterKey.GetValue ("MyKey"));
}
masterKey.Close();
Tuesday, April 8, 2008
Partial classes
This is a feature of 2005,when we have large and unwildly classes instead of writing all the methods in same program we will divide the class into number of programs with the same class name,these classes are preceeded with partial keyword,when we compile all this partial classes only one dll with the same class name will be created.
class with some 20 methods:
Example.cs
class classA{
m1( );
m2( );
.
.
.
m20( );
}
Apply partial concept:
Example1.cs
partial class classA
{
m1( );
m2( );
.
.
m8( );
}
example2.cs
partial class classA
{
m9( );
m10( );
.
.
m15( );
}
Example3.cs
partial class classA
{
m16( );
.
.
m20( );
}
if we compile Examle1.cs,Example2.cs,Example3.cs it will create only one dll
Sunday, March 30, 2008
printers connected to your computer
This code sample gets you the list of all connected printers (both local and network printers).
Microsoft.Win32.RegistryKey rk;
rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Printers\Settings");
string[] printernames = rk.GetValueNames();
if (printernames.Length > 0)
{
foreach (string s in printernames)
{
{
Console.WriteLine(s);
}
}
}
Convert Database data to XML
The data existing in the relational database can be easily converted into an xml documant in the program. The following code illustrates this.
I have used SQLServer database table employee ( with columns empid, first_name,last_name,deptcd,salary and resig_status) The connection is established using appropriate connection string. The data from the RDBMS table is stored in the dataset dsEmp. The xml class XmlDataDocument is used to convert the data into an xml data file. It takes the dataset as input and converts to xml data.
{
DataSet dsEmp = new DataSet();
string strCon;
string strSelect;
strCon = "data source=SQLEXPRESS;initial catalog=dbemp;persist security info" +
"=False;user id=sa;password=jadoogar;workstation id=HCL;packet size =4096";
strSelect = "Select empid,first_name,deptcd from employee";
try
{
SqlConnection sqlCon = new SqlConnection(strCon);
SqlDataAdapter empAdapter = new SqlDataAdapter(strSelect,sqlCon);
empAdapter.Fill(dsEmp,"employee");
}
catch
{
}
XmlDataDocument empDoc = new XmlDataDocument(dsEmp);
empDoc.Save(MapPath("xmldata/newemp.xml"));
}
Wednesday, January 16, 2008
AndAlso & OrElse Operators in C#
AndAlso(&&)
The logical operator && is the AndAlso in C#. This is used to connect two logical conditions checking like if (
int a = 100;
int b = 0;
if (b > 0 && a/b <100)
{
Console.Write("ok");
}
The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check and our "&&" operator won't perform the second condition checking. So actually our execution time is saving in a logical operation in which more conditions are combined using "&&" operator.
And(&)
The difference of "&" operator compared to above is mentioned below
int a = 100;
int b = 0;
if (b > 0 & a/b <100)
{
Console.Write("ok");
}
The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check. But our "&" operator will perform the second condition checking also. So actually our execution time is losing for a useless checking. Also executing the "a/b <100" unless b>0 is generating an error also.
Or(|) and OrElse(||)
The difference of Or ("|") and OrElse ("||") are also similar to "And" operators, as first one will check all conditions and second one won't execute remaining logical checking, if it's found any of the previous checking is true and saving time. You can analysis these by the below code.
//Or
if (b > 0 | a/b <100)
{
Console.Write("ok");
}
//OrElse
if (b >= 0 || a/b <100)
{
Console.Write("ok");
}
Thursday, January 3, 2008
Partial Classes
Partial classes allows you to have multiple pieces of a class definition. Functionally, partial classes are not at all different from classes written as full classes. Which means you can have one single class definition or a class written as a few distinct parts, without breaking existing functionality.
How Partial Classes Work
The basic idea of a partial class is very easy to understand. You keep the definition of a class split into pieces. During the compilation of the code, the compiler will finds all of the pieces of the class and lump them together. This task accomplished by the compiler removes that separation, so functionally there is no difference between a class made of partial classes and a whole class.
Creating Partial Classes
Partial classes allow you to separate code for a class into multiple class definitions. So as an example I will write a few class definitions. One will be a whole definition of a class without using partial classes, and the other one will be the same class split into two partial classes.My single definition class of AIPlayer.
Listing 1: A Standard Class
public class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
public Move GetMove()
{
// Choose the best move and return it.
}
}
Listing 2: A Class Split Into Two Partial Classes
public partial class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
}
public partial class AIPlayer
{
public Move GetMove()
{
// Choose the best move and return it.
}
}Without having the partial keyword in there I would probably get a compiler error. The reason for this is that I would be declaring two different classes in the same namespace with the same name, and that would generate the error. Since I have the partial keyword there, the compiler knows that I am just extending the existing class. It will take that into account and will combine the code before trying to compile it.
As a note, make sure to use the partial keyword on ALL definitions of the class even the original one. This is not necessary for VB, but in C# all of the classes must have the partial keyword. I think it is great that this is included, because it is a hint to a programmer that there might be another piece of a class somewhere else. If you ever see the partial keyword on classes you're working with, it is a nice warning that there might be more to the class elsewhere.
When to Use Partial Classes
There are plenty of cases where a partial class can assist you in developing your applications. Most people have already seen them and might not have noticed them in ASP.NET pages, because you don't actually need to know that it is using these partial classes in order to use them. They're also quite popular being used alongside generated code, because it lets people modify the generated code. Sometimes people will also use it when working in larger groups who will not be committing code often. This is because it lets them make large amounts of changes without having painful merges later.
