Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, December 17, 2015

What is interface in programming.



In real world, we see objects everywhere, and we interact with them by their interfaces.
For example: we start our computer by on/off button. Every computer has on/off button. User just find the on/off button and start it.  

Engineers make things, things has many complexities inside, engineers makes interface to simplify the complexities. So user can easily use those things.

Software engineers creates classes for objects, a class may have several methods, properties, events and other complexities. Software engineer provides an interface for this class, so the other software engineers can easily interact with this class by their interface.

Interface contains only signatures of methods, properties, events and indexers. Interface just a template, it does not contain definitions. Any class which implements the interface must implements the every method defined in the interface.

In real world almost every device has on/off button. So we design a simple interface for our device classes.

Interface contains only signature of methods.
Public interface IDevice{
            Public void toggleOnOff();
}

We have designed two different type of classes for our devices, both use same interface, both implements same methods but different definition as per device requirement.

Public class DesktopDevice:IDevice{
          Public void toggleOnOff(){
                        // just press the button.
                        // code.
              }
}

Public class SmartDevice:IDevice{
          Public void toggleOnOff(){
                        // press the button for 3 seconds
                        // code.
          }
} 

Usage for desktop devices.
IDevice dDevice = new DesktopDevice();
dDevice.toggleOnOff();

For Smart Devices.
IDevice sDevice = new SmartDevice();
sDevice.toggleOnOff();











Tuesday, October 20, 2015

Monday, October 19, 2015

C#: Converting Object in to JSON

This is not the single way to serializing object into JSON, but the simple way is to do that. 

1. Download the Newtonsoft JSON serializer. 
2. Reference the DLL. 
3. Using the namespace in your class. 


C# Code. 


namespace:

using Newtonsoft.Json;


 public string GetData(string name)
        {
            person p = new person();
            p.name = name;
            return JsonConvert.SerializeObject(p);
        }
    }