Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

Saturday, January 28, 2017

CSharp - Read data from a text file

Read data from a text file.

Reading data from a text file in C# is pretty straight forward. The namespace that contains classes that you can use to perform input/output operations is "System.IO". To read data you can use the StreamReader class that provides many methods of reading data. Please refer to MSDN for details on the constructors of StreamReader.

In the example below, I am reading data from a text file called "data.txt". Since StreamReader class implements the IDisposable interface you can explicitly call the Dispose() method once you have finished reading the file or use can use the using{} construct which automatically disposes the StreamReader object.


Sample Code


using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
           static void Main(string[] args){
                ReadTextFile(); 
                Console.Read();
        }

        private static void ReadTextFile()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("C:\\data.txt"))
                {
                    string dataLine;
                    while ((dataLine = streamReader.ReadLine()) != null)
                    {
                        Console.WriteLine(dataLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Unable to read the file");
                Console.WriteLine(ex.Message);
            }
        }
    }


1. using (StreamReader streamReader = new StreamReader("C:\\data.txt"))

The above line creates a new instance of StreamReader and puts a handle on the file located on C:\data.txt.


2. string dataLine;
    while ((dataLine = streamReader.ReadLine()) != null)
    {
            Console.WriteLine(dataLine);
    }

A variable dataLine is declared to hold each line read from the file. We  then call the ReadLine() method on the streamReader instance we created. 

The ReadLine()  method reads the whole line of characters and return the result as a string object. The result is stored in the dataLine variable. 

The value is then checked for null which checks if we have reached the end of the file. If this is not the case the value of the dataLine is output to the Console screen.

If a null is returned the loop condition fails and we don't attempt to read any further.

At the closing bracket of the using {....} construct the stream is disposed and the file to the handle is removed.

Note: Use the using {....} construct in you code to avoid memory leaks and fixing bugs later in the software life cycle.

Read the file in a single statement


If you don't want to read the file line by line, StreamReader provide another function to read data in a single go and return it as string. Use the ReadToEnd() method for such a scenario.

        private static void ReadTextFileAgain()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("d:\\data.txt"))
                {
                    string dataLine;
                    if ((dataLine = streamReader.ReadToEnd()) != null)
                    {
                        Console.WriteLine(dataLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Unable to read the file");
                Console.WriteLine(ex.Message);
            }
        }



Sunday, June 12, 2016

CSharp Data Types

Data Types in C#

C# is a strongly typed language. This means every variable you declare has a type associated to it. The types specifies the size and location of memory. The types available in C# are simple (a.k.a value) types and reference types.

Simple Types or Value Types

Value types are variables that are based on System.ValueType. These types actually contains the value in them. They are the boxes that keep the value inside the box. If the type of variable is any one of the built-in data types like int, char, string and so on, then that value of that variable will be stored on a stack which is a highly efficient memory.

C# Value or Simple Types

Name Size Range (Min - Max)
byte 8 bit integer (Unsigned) 0 to 255
sbyte 8 bit integer (Signed) -128 to 127
char 16 bit (Unicode) U+0000 to U+FFFF
int 32 bit integer (Signed) -2,147,483,648 to 2,147,483,647
uint 32 bit integer (Unsigned) 0 to 4,294,967,295
long 64 bit integer (Signed) –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 64 bit integer (Unsigned) 0 to 18,446,744,073,709,551,615
short 16 bit integer (Signed) -32,768 to 32,767
ushort 16 bit integer (Unsigned) 0 to 65,535
double 15 to 16 digits precision ±5.0 × 10−324 to ±1.7 × 10308
decimal 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)
float 7 digits precision -3.4 × 1038to +3.4 × 1038
bool Boolean value true or false

C# Reference Types

Unlike value types that contain the value within them, reference types are variable whose value is a memory address. This memory address may actually point to the value stored on the heap.

Reference types are also called complex types in that you define it by combining one or more of the built-in or other reference types.

Complex types derive from Object type which is the base class for all reference types. We will look at Object Oriented Principles later in the series.

Reference types are housed in a heap memory and requires a non deterministic approach for memory management like garbage collection.

To put it simply, if you have an object of type Cat and you name it Daisy, here Daisy is a pointer to a place in the heap which contains the data for a type Cat. Lets look at an example.

public class Cat {
    public string name {get; set;}
    public string colour {get; set;}
}

The above code defines a Cat type with two attribute name and colour.

Cat daisy = new Daisy();
daisy.name = "Daisy Jr'";
daisy.age = 4;

The above 3 lines creates a Cat object whose reference name is daisy. This reference points to an object with two string values on the heap. If you create another Cat named kitty and assign the it daisy, then daisy and kitty will point to the same memory location on the heap.

 In simple words, reference types refer to something on the heap whereas a value types occupies its place on a stack.

Tuesday, May 3, 2016

CSharp Constants

What are constants

A constant also refers to name assigned to a memory in your computer like a variable but with a subtle difference; its value can only be assigned once. Yes, the value is assigned to the memory at compile time and it cannot be changed.




How do we declare constants in C#


Exactly like you declare variables but you put one extra prefix "const" to your declaration.

This is a variable declaration with assignment.

int speedOfLight = 299792458; /*meters per sec*/

You can change the value of the above variable.

speedOfLight = 670616629; /*miles per hour*/

This is a constant declaration with assignment.

const double pi = 3.14159265358979323846264338327950;

Assignment to a constant will cause a compile time error as you can only assign values to variables, properties or indexers.

Here comes the concept of lvalue and rvalue. Look at the example below:

lvalue = rvalue
x = 10; 

The lvalue is an expression that can be placed on the left or right of the expression.

In the expression x=10, the lavlue is x and rval is 10
x will have no problem if you write
int y = x; 

The rvalue of the expression can only be placed on the right side of the expressions.
So, if you write 10=x, this would not compile as 10 is not a variable, its a literal which can only sit on the right side.


CSharp Variables

What are variables in general


In any programming language, a variable refers to a space in the computers memory. We give this space a meaningful name so that we can refer to that memory in our code easily without causing any confusion. 




Assigning a value to a variable means that we intend to put a value in the memory identified by the variable.


How to declare variables in C#


The syntax in C# to declare a variable is to first write the type and then its name like so:


typeOfVariable nameOfVariable;

            int counter;
            string name;
            double price;



Declare and Assign a value at the same time



You can declare and assign the value to a variable in a signle step like so:

typeOfVariable nameOfVariable = thevalueofthevariable;

These are some good examples of variable declarations with value assignment.

            int counter = 0;
            string name = "Your Name";
            double price = 24.99d;

These are some bad examples of variable as their names do seem to be meaningful:
            int x = 0;
            string theVariable = "Your Name";
            double p = 24.99d;

Saturday, April 30, 2016

CSharp Statements and Expressions

CSharp Statements and Expressions

In C# a statement is a line of code which form part of the program flow. Each line of code may perform an action or it may contain a non-action piece of code. Lets see how many types of C# statements we may write and then we will see a complete program using all these types of statements.

Types of Statements

  1. Declare Statements
  2. Assignment Statements
  3. Function Call Statements
  4. Return Statements
  5. Break Statement
  6. Conditional Statements
  7. Loop Statements

Expressions in C# are a combination of one or more variables, operators, a function call that would be processed and gives back a value. This value may be used by other expressions or contexts. Below are few examples of expressions

  • a>10
  • x = 2+3;
  • counter == 100
  • Math.Pow(2,4);


Lets try to understand them with example program. You can copy this program into a Visual Studio Console Application Project. Copy the code into Program.cs file and you are good to go. Hit F5 and you have an interactive application.

Example:


using System;
namespace SampleConsoleApp
{
    class Program
    {
        static void Main()
        {

            //Declare Statements

            double counter;

            string DoWhat; //1: Calculate Power, 2: Mutiply


            //Assignment Statements 

            counter = 10;
            DoWhat = "";

            while (true)

            {
                Console.WriteLine("");
                Console.WriteLine("Press One of these Options");
                Console.WriteLine("1. Power Calculation");
                Console.WriteLine("2. Multiples");
                Console.WriteLine("3. Say Hello");
                Console.WriteLine("0. Exit");
                DoWhat = Console.ReadLine();

                Console.WriteLine("You selected " + DoWhat);


                if (DoWhat.Equals("1"))  //Conditional Statements

                {
                    for (double i = 0; i < counter; i++) //Loop Statement and Expressions
                    {
                        PrintPower(i, (i - 2)); //Function Call Statement
                    }
                }
                else if (DoWhat.Equals("2"))  //Conditional Statements
                {
                    for (int times = 0; times < 5; times++) //Loop Statement
                    {
                        PrintMultiples(times, 6);//Function Call Statement
                    }
                }
                else if (DoWhat.Equals("3"))  //Conditional Statements
                {
                    SayHello();
                }
                else if (DoWhat.Equals("0"))  //Conditional Statements
                {
                    break; //Break Statement
                }
                else  //Conditional Statements
                {
                    Console.WriteLine("Invalid Input. Try Again");
                }
            }

            Environment.Exit(0);

        }

        private static void SayHello()

        {
            Console.WriteLine("Hello There");
        }

        private static void PrintMultiples(int i, int j)

        {
            Console.WriteLine("{0} x {1} = {2}", i, j, i * j);
        }

        private static void PrintPower(double i, double PowerOf)

        {
            try
            {
                Console.WriteLine("{0} to the power of {1} is {2}", i, PowerOf, Math.Pow(i, PowerOf));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Press Enter to EXIT");
                Console.ReadLine();
                Environment.Exit(1);
            }
        }
    }
}


Here is the program output





Tuesday, April 26, 2016

CSharp Your first CSharp program dissected

Your first CSharp program


Hello and Welcome to this C# multi-part series. We are going to start from the basics of C# language and get down to coding without getting deep into the history.


What you need to write and run the programs:
Download Free Visual Studio Community edition





















This is our first C# sample program.

 using System;

 namespace SampleConsoleApp
 {
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Hello World");
         Console.ReadLine();
     }
   }
 }

Lets dissect it for a moment line by line.


1 using System; 


This is the bare minimum required by a C# executable. The statement means I want to use the namespace "System" and everything in it. Whats a namespace? Its a logical division of an application. Your code can exist in a single name space or span many. We will get to that in the next tutorials.


2 namespace SampleConsoleApp


This is my programs namespace called "SampleConsoleApp". This namespace contains the code that I wrote. 


3 {


Starting of my namespace "SampleConsoleApp"


4   class Program

I am declaring a class called Progam. You can use any name you like. Classes are simply template for objects that you create when needed. We will discuss classes and objects later in the course as part of object oriented programming.

5   {

Start of my namespace "Program"

6      static void Main(string[] args)

This is the entry point to the program. You can have only one Main method in this type of application. The string[] args is used to pass data that your program may need to run. You can also skip writing 

7      {

Start of my Main method

8         Console.WriteLine("Hello World");

Prints "Hello World" on the console.

9         Console.ReadLine();

Makes your program to wait for an input <ENTER>.

10      }

Ending of Main method

11   }
Ending of my namespace "Program"

12 }
Ending of my namespace "SampleConsoleApp"


To run this program just hit Ctrl+F5 or goto Debug menu and select Start Without Debugging on your visual studio and you should see "Hello World" on the console window.




Happy programming.


Please feel free to post comments, like and subscribe.