Showing posts with label c# functions. Show all posts
Showing posts with label c# functions. Show all posts

Default Access Modifiers in C#

top level class: internal

method: private

members (of class): private (including nested classes)

members (of interface or enum): public

constructor: private (note that if no constructor is explicitly defined, a public default constructor will be automatically defined)

delegate: internal

interface: internal

Read more...

Must declare the scalar variable @variableName c# Sql


When u need to pass parameters to sql Query. This can be done in two ways..

First one:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

string query = "select * from table where columnName = '" + txtSearch.Text + "'";

SqlCommandcommand = new SqlCommand(query,connection);

Bur this approach is not recommended. this may lead to error sometimes. So, whenever we need to pass parameters to query, use SqlParamater. The same query can be written as..

string query = "select * from table where columnName =@value";

SqlCommand command = new SqlCommand(query,connection);

command.Parameters.AddWithValue("@value",txtSearch.Text);

Using SqlParameters gives a cleaner, less error prone and SQL injection safe (comparative) code.


Read more...

LINQ Single and SingleOrDefault



Single means you are expecting only one result from LINQ query. If you get more than one or zero matches, then it throws exception.

SingleOrDefault means if you get single result, it returns that result but if it doesn't find any matches it returns default value but you will not get any exception.
Read more...

Return only one result from LINQ Query

You can do it in two ways, either use First or use Single.

First returns only first row, even there are multiple rows

Single expects only one row to be returned, and if there are multiple rows, it throws exception.

So, use Single if you are expecting only one row to be returned.

EX: var book= from book in store where (book.price > 100) select book).First();
Generally , the query returns all books having price greater than 100. but , as we are using  " .First() " only first book will be returned.


Read more...

return more than one value from a method


We can't return more than one values from a method.

An alternative way would be, add all those values to be returned into  Array and return that array.

Ex: public int[] returnArray ()
{
int[] myArray=new int[3];
myArray[0] = value1;
myArray[1] = value2;
myArray[2] = value3;

      return myArray;
}

Read more...