Friday, July 12, 2013

 public class Ulke
    {
        public int nufus;
        public int yuzolcumu;
        public string komsular;
        public void Denizler() { }
    }

    public class Sehir:Ulke
    {
        //Inheritance ornegi
        public int ilcesayisi;
        public  int otobussayisi;

    }

    class Program
    {
        static void Main(string[] args)
        {
            Ulke Turkiye = new Ulke(); // Ulke turunde bir class olan Turkiye'yi construct etmis olalim
            Turkiye.komsular = "Suriye"; // Komsular field ini tanimla
            Turkiye.yuzolcumu = 783; // yuzolcumu field ini tanimla
            Turkiye.nufus = 74; // nufus fieldini tanimla

            Sehir Istanbul = new Sehir(); // Sehir turunde bir class olan Turkiye'yi construct etmis olalim

            Istanbul.nufus = 15; // Istanbul'un nufus fieldini tanimla
            Istanbul.komsular = "Yalova";
            Istanbul.ilcesayisi = 23; // Istanbul'un ilcesayisi field'ini tanimla

            //Polymorphism ornegi
            Ulke Karadeniz = Istanbul;
            // Karadeniz objesi Ulke turunde bir nesne ancak
            // Poly-morph ederek Istanbul'a ait ancak Ulkeden inherit edilmis fieldlari
            // Karadeniz inherit ediyor
            // Yani her ne kadar Karadeniz Sehirin ust classi olan Ulke classinda bir object de olsa
            // Sehir classinin bir nesnesi olan Istanbulun field larini almis oluyor

            Console.WriteLine(Karadeniz.nufus); // Istanbulun nufusu
            Console.WriteLine(Karadeniz.komsular); // Istanbulun komsulari
            //Console.WriteLine(Karadeniz.ilcesayisi) Istanbulun ilce sayisi tanimli oldugu halde Karadeniz Ulke
            // class'ina ait oldugundan dolayi ilcesayisi field'i olamaz.
            Console.ReadKey();

            //Ozetle polymorphism yeni yaratilan bir nesnenin, kendisinden once tanimlanmis
            //bir nesneden field lar alabilmesi ancak bu (field larin kopyalandigi) nesne ile
            //farkli siniflarda olabilmesidir.


        }
    }

Posted on 8:10 PM by Erdem

No comments

Thursday, July 11, 2013

In C# all methods must be declared inside a class. However, if you declare a method or field as static, you can call the method or access the fields by using the name of the lass. No instance is required.

class RFClass
    {
        public static double converter(double inp1)
        {
            return inp1 * 3;
        }
    }

dedigin zaman, main fonksiyon icindeyken asagidaki komut calisiyor;
 double d2 = RFClass.converter(423);



Creating a Shared Field in a class
-- Objenin icindeki variable a field denir

When defining a field, you can use the static keyword so the field becomes available to all methods in an object, hence becoming shared field.


Creating a static field with const Keyword
When you define a field with const keyword, it automatically becomes static - available to all methods or outside calls- but can not be changed since it's defined as a constant. You can only define int, double or string as a constant



Static Class
In order to use as a utility class, hold variables and call methods, you can also define a static class.



Ama sadece class'i static olarak define edip de field lari static olarak tanimlamazsak onlar otomatikman statik olmuyorlar.. Yani

    public static class StaticClass1
    {
        public int dem = 0;
        public double demd = 0.0412;
    }

dedigimizde, dem veya demd disardan accessible static variable lar olarak islemiyor.

Posted on 12:46 PM by Erdem

No comments

A constructor is a special method that runs automatically when you create an instance of a class. It has the same name as the class and it can take parameter but it can not return a value..

If you don't write your own constructor, the compiler will generate a constructor for you.

If a constructor is not public, it can't be used outside of a class and it can't be called by methods that are not a part of the class.

What's the use of making a constructor private:
  1. The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
  2. A utility class, that only contains static methods.

Overloading Constructors
You can overload constructors as you can overload any method.

Posted on 12:05 PM by Erdem

No comments

class Circle
{
              int radius;
              double Area()
              {
                            return Math.PI*radius*radius;
              }
}

Circle c;
c = new Circle();

// When you use new keyword to create an object, the runtime has to construct that object by using the definition of the class. A constructor is a special method that runs automatically when you create an instance of a class.

What is a constructor
What is instance of a class

Posted on 11:06 AM by Erdem

No comments

How much memory does a class use?
How much memory does a function use?

Posted on 10:36 AM by Erdem

No comments

Kisacasi encapsulation, classlarin bir kismini erisilebilir bir kismini erisilemez yaparak programcinin daha rahat bir sekilde class lari kullanmasini saglamaktir.

Posted on 10:30 AM by Erdem

No comments

http://www.adobe.com/devnet/actionscript/learning/oop-concepts/encapsulation.html

Encapsulation

When you create an object in an object-oriented language, you can hide the complexity of the internal workings of the object. As a developer, there are two main reasons why you would choose to hide complexity.
The first reason is to provide a simplified and understandable way to use your object without the need to understand the complexity inside. As mentioned above, a driver doesn't need to know how an internal combustion engine works. It is sufficient to know how to start the car, how to engage the transmission if you want to move, how to provide fuel, how to stop the car, and how to turn off the engine. You know to use the key, the shifter (and possibly clutch), the gas pedal and the brake pedal to accomplish each of these operations. These basic operations form an interface for the car. Think of an interface as the collection of things you can do to the car without knowing how each of those things works.
Hiding the complexity of the car from the user allows anyone, not just a mechanic, to drive a car. In the same way, hiding the complex functionality of your object from the user allows anyone to use it and to find ways to reuse it in the future regardless of their knowledge of the internal workings. This concept of keeping implementation details hidden from the rest of the system is key to object-oriented design.
Take a look at the CombustionEngine class below. Notice that it has only two public methods: start() and stop(). Those public methods can be called from outside of the object. All of the other functions are private, meaning that they are not publicly visible to the rest of the application and cannot be called from outside of the object.
package engine { public class CombustionEngine { public function CombustionEngine() {} private function engageChoke():void {} private function disengageChoke():void {} private function engageElectricSystem():void {} private function powerSolenoid():void {} private function provideFuel():void {} private function provideSpark():void {} public function start():void { engageChoke(); engageElectricSystem(); powerSolenoid(); provideFuel(); provideSpark(); disengageChoke(); } public function stop():void {} } }
You would use this class as follows:
var carEngine:CombustionEngine = new CombustionEngine(); carEngine.start(); carEngine.stop();
The second reason for hiding complexity is to manage change. Today most of us who drive use a vehicle with a gasoline-powered internal combustion engine. However, there a gas-electric hybrids, pure electric motors, and a variety of internal combustion engines that use alternative fuels. Each of those engine types has a different internal mechanism yet we are able to drive each of them because that complexity has been hidden. This means that, even though the mechanism which propels the car changes, the system itself functions the same way from the user's perspective.
Imagine a relatively complex object that parses an audio file and yet allows you only to play, seek or stop the playback. Over time, the author of this object could change the internal algorithm of how the object works completely—new optimization for speed could be added, memory handling could be improved, additional file formats could be supported, and the like. However, since the rest of the source code in your application uses only the play, seek and stop methods, this object can change very significantly internally while the remainder of your application can stay exactly the same. This technique of providing encapsulated code is critical in team environments.
Take a look at the refactored CombustionEngine class below. Over time, technology has improved. Instead of having a manual choke and carburetor, it now uses fuel injection. The internal system has therefore changed dramatically. Notice that it still only has two public methods: start() and stop() . The rest of your system will remain the same even though the internals of your engine changed. Imagine that you have a relatively complex application that uses the engine from hundreds of places. Not having to update each of those places when you change engines could save many days of work.
package engine { public class CombustionEngine { public function CombustionEngine() {} private function engageElectricSystem():void {} private function powerComputer():void {} private function powerSolenoid():void {} private function provideFuel():void {} private function provideSpark():void {} public function start():void { engageElectricSystem(); powerComputer(); powerSolenoid(); provideFuel(); provideSpark(); } public function stop():void {} } }
You would use this class as follows:
var carEngine:CombustionEngine = new CombustionEngine(); carEngine.start(); carEngine.stop();

Implicit getters and setters

ActionScript 3 has a concept of implicit getters and setters which allows you to further hide implementation details from the user when setting or reading a property. Look at the following class which represents a Person . This class uses the method updateDisplay() to refresh what is displayed on the screen. When you update the Person's first name or last name, you need to remember to call the updateDisplay() method to ensure the screen is updated with the Person's new name.
package people { public class Person { public var firstName:String; public var lastName:String; public function Person(){} public function updateDisplay():void { trace( firstName + " " + lastName ); } } }
You would use this class in the following way:
var person:Person = new Person(); person.firstName = "Lee"; person.updateDisplay(); //output: Lee null person.lastName = "Alan"; person.updateDisplay(); //output: Lee Alan
In this example, any place in your code where you update either the first or last name, you also need to remember to callupdateDisplay() . Not only is it easy to forget, but if this was a more complicated object, you might cause strange situations where the object is out of sync if you update part of it, but not the rest.
ActionScript 3 allows you to hide complexity while solving both of the above problems with implicit getters and setters. An implicit getter and setter is really two functions that look like a single property to the user of the object. One function— the getter—is called when a property is read. The other function—the setter—is called when a property is set. Together, these functions allow users of your class to access private properties as if they were accessing public properties. Additionally, the access is provided without having two public functions for each private property that provide read and write access.
An added benefit of a setter function is that it provides a convenient place to ensure that data is formed in a way that is expected by your object. Using a setter function, an object can potentially validate the data before it is stored internally, reducing the need to further check the data each time it is used and providing some measure of consistency to the object's internal state.
In the following code, the firstName and lastName public variables have been converted to private properties with implicit getters and setters. Now, whenever the firstName or lastName is set, the String value is checked to ensure it is not null and that it has characters before the value is assigned to the property. Then the updateDisplay() will automatically be called. There is no chance that the user can forget to call the updateDisplay() method. Further, theupdateDisplay() method has been made private so that users of the object cannot call it directly. That functionality has been encapsulated because the user does not need to know how the object works internally.
package people { public class Person { private var _firstName:String; private var _lastName:String; public function Person(){} public function get lastName():String { return _lastName; } public function set lastName(value:String):void { if(value!=null && value.length>0){ _lastName = value; updateDisplay(); } else{ trace("Invalid name"); } } public function get firstName():String { return _firstName; } public function set firstName(value:String):void { if(value!=null && value.length>0){ _firstName = value; updateDisplay(); } else{ trace("Invalid name"); } } private function updateDisplay():void { trace( firstName + " " + lastName ); } } }
As you can see above, to create a getter and setter for a property, you first create a private variable to hold the value. In this case, that private variable is named _lastName . The underscore is a variable naming convention which indicates that _lastName is private and cannot be seen outside of the class.
private var _lastName:String;
Next, you create two functions. One uses the keyword get , which will be called automatically when you read the property, and one uses the keyword set which will be called automatically when the property is set. Note that the get function accepts no arguments and returns the same type as the _lastName variable. The set function accepts a single argument of the same type as the _lastName variable, assigns that argument to _lastName if the argument passes the conditional test, and returns nothing.
public function get lastName():String { return _lastName; } public function set lastName(value:String):void { if(value!=null && value.length>0){ _lastName = value; updateDisplay(); } else{ trace("Invalid name"); } }
You would use this class in the following way:
var person:Person = new Person(); person.firstName = "Lee"; //output: Lee null person.lastName = "Alan"; //output: Lee Alan person.firstName =; //output: Invalid name
The firstName and lastName properties still look like simple variables to the user of this class; however, you now have the ability to do additional work when either is called. In this example, the argument is checked and theupdateDisplay() method is called, but now it is done implicitly instead of explicitly, removing the possibility of user error and hiding the implementation details

Where to go from here


Encapsulation is one of the most important and most advantageous concepts provided in object-oriented programming. By taking proper care when designing your objects to hide their internal details from the rest of the system, you gain the ability to simplify the remainder of the system while isolating it from problems caused by changes to the internal structure of your objects.
These concepts are absolutely critical when working with a team. 

Posted on 7:21 AM by Erdem

No comments

Wednesday, July 10, 2013

A language mechanism for restricting access to some of the object's components.


Posted on 7:29 AM by Erdem

No comments

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ThousandNumbersIO { class Program { static void Main(string[] args) { printnumbers(10); readnumbers(); Console.ReadKey(); } static void printnumbers(int num1) { Random rnd = new Random(); int int1; string[] lines = { "First line", "Second line", "Third line" }; using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines.txt", true)) for (int ii = 0; ii < num1; ii++) { int1 = rnd.Next(1, 10); file.WriteLine(Convert.ToString(int1)); } } static void readnumbers() { // The files used in this example are created in the topic // How to: Write to a Text File. You can change the path and // file name to substitute text files of your own. // Example #1 // Read the file as one string. string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteLines.txt"); // Display the file contents to the console. Variable text is a string. System.Console.WriteLine("Contents of WriteText.txt = {0}", text); // Example #2 // Read each line of the file into a string array. Each element // of the array is one line of the file. string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt"); // Display the file contents by using a foreach loop. System.Console.WriteLine("Contents of WriteLines2.txt = "); foreach (string line in lines) { // Use a tab to indent each line of the file. Console.WriteLine("\t" + line); } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } }

Posted on 7:29 AM by Erdem

No comments

Tuesday, July 09, 2013

namespace Study_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            string st1 = "This is a string";
            int[] int1 = {2,3};
            int int2;
            char[] c1;

            try
            {
                st1 = Console.ReadLine();
                int st2;
                st2 = st1[231];
            }
            catch (System.IndexOutOfRangeException ex)
            {
                Console.Write("Index is out of range");
            }
            catch (System.AccessViolationException ex)
            {
                Console.WriteLine("AccessViolationException");
            }
            finally
            {
                Console.WriteLine("Did we even get here?");
            }
            Console.ReadKey();


        }
    }
}

Posted on 8:33 PM by Erdem

No comments

Posted on 7:06 PM by Erdem

No comments

Monday, July 08, 2013

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;

namespace DrawARectangle2
{




    public partial class Form1 : Form
    {

        private static System.Timers.Timer aTimer;
        public static int t_msec = 0; // tenmiliseconds
        public static string formattime;
        public static int rad = 3;
           

        public Form1()
        {
            InitializeComponent();
        }



        private void DrawIt()
        {
           
            System.Drawing.Graphics graphics = this.CreateGraphics();
            this.Invalidate();
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
                100, 100, rad, 150);
            graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
   
        }

        private void button1_Click(object sender, EventArgs e)
        {
        aTimer = new System.Timers.Timer(1);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        //aTimer.Interval = 2000;
        aTimer.Enabled = true;
        }

        private void OnTimedEvent(object sender, EventArgs eArgs)
        {        
            DrawIt();
            rad++;
        }


    }
}

Posted on 1:56 PM by Erdem

No comments

 class Program
    {

        //This function will work fine with an assigned variable
        //However it will not work with an unassigned variable
        static void testfun1(ref int maya)
        {
            Console.WriteLine(maya);
            maya = 3;
        }

        //This function will work fine with a defined variable but assignment is not mandatory
        static void testfun2(out int maya)
        {
            maya = 4;
        }


        static void Main(string[] args)
        {
            int dedo = 12;
            int dedo2;
            // testfun1(ref dedo2); will not compile since dedo2 is not assigned
            Console.WriteLine("Test for Erdem");
            Console.WriteLine(dedo);

           
            testfun2(out dedo2); // this will be fine
            Console.WriteLine(dedo2);

            Console.ReadKey();
        }
    }

Posted on 7:46 AM by Erdem

No comments

Wednesday, July 03, 2013

http://stackoverflow.com/questions/3615800/download-image-from-the-site-in-net-c


string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}


Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:
private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

Posted on 1:54 PM by Erdem

No comments