Valid XHTML 1.0 Stdict

Ověřit CSS!

C#

Čo je C#:

C# (v angličtine si-sharp) je objektovo-orientovaný programovací jazyk vyvinutý spoločnosťou Microsoft ako časť ich iniciatívy .NET. Microsoft si za základ pre nový jazyk C# zobral C++ a jazyk Java. C# bolo navrhované s úmyslom vyvážiť silu jazyka C++ a tú spojiť s možnosťou rýchleho programovania "rapid application development", ktoré ponúkali jazyky ako napríklad Visual Basic, Delphi.

Vývojové prostredie:


MicrosoftR Visual C# 2010 Express

1.príklad:

Konzolovú aplikáciu vytvoríme po kliknutí v paneli nástrojov File -> New Project -> Console Application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

Dátové typy:

Operátory:

Logické operátory:

Štruktúry

2.príklad:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public struct Osoba
    {
        private string meno;
        private int vek;
        private int vyska;
        public Osoba(string meno, int vek, int vyska)
        {
            this.meno = meno;
            this.vek = vek;
            this.vyska = vyska;
        }
        public string getMeno()
        {
            return this.meno;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Osoba student = new Osoba("peto", 24, 167);

            string name = student.getMeno();

            Console.WriteLine(name);
            Console.ReadLine();

        }
    }
}

Enumeračné typy

Vymenovania (enumeration) je užívateľom definovaný celočíselný typ. Znamená to, že programátor si na začiatku programu definuje sadu hodnôt, ktoré môže používať pre dané vymenovanie a keďže sa jedná o celočíselný typ, tak vo vymenovaní môže použiť iba hodnoty celých čísel.

3.príklad:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[Flags]
public enum Den
{
    pondelok, utorok, streda,
    stvrtok, piatok, sobota,
    nedela
};

class MainClass
{
    public static void Main(string[] args)
    {
        Console.WriteLine(" Den po pondelku je {0}",Den.pondelok + 1);
        Console.ReadLine();
    }

   
}

Odkazové dátové typy

String

4.príklad:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "Peter";
            string s2 = "Zahorak";
            int vek = 24;

            string s3 = vek.ToString();
            string s4 = s1 +"  "+ s2+"  "+s3;
           
            char c1 = s1[0];
            char c2 = s2[0];

            Console.WriteLine(s4); 
            Console.WriteLine(c1+"."+c2+".");


            Console.Write("zadaj meno: ");
            string st1 = Console.ReadLine();
            Console.WriteLine(st1); 

            Console.Write("zadaj priezvisko: ");
            string st2 = Console.ReadLine();
            Console.WriteLine(st2);
 
            Console.Write("zadaj vek: ");
            string age = Console.ReadLine();
            
            Console.WriteLine(st1 + " " + st2 + " " + age);
           
            Console.ReadLine();
        }
    }
}
      

5.príklad:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string st = "          medzera ";
            Console.WriteLine(st);
            st = st.Trim();
            Console.WriteLine(st);

            Console.ReadLine();
            
        }
    }
}

6.príklad:

   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string text1 = "pocitac";
            string text2 = "POCITAC";
            string text3 = "P o c i t a c";
            int zhodne;
            bool IgnoreCase = true;

            zhodne = String.Compare(text1, text2);
            Console.WriteLine(zhodne); //-1 
            zhodne = String.Compare(text1, text2, IgnoreCase);
            Console.WriteLine(zhodne); // 0 
            zhodne = String.Compare(text1, text3);
            Console.WriteLine(zhodne); // 1  
            Console.ReadLine();

        }
    }
}
       
       

Základné príkazy jazyka C#

podmienka:

 
if (vyraz)
{
  príkaz
}
else
{
  príkaz
} 

cyklus for:

 
for ( int i = 0; výraz;i++ )
{ 
  príkaz 
} 

cyklus while:

 
while (výraz)
{
  príkaz
} 

cyklus do while :

 
do
{
  príkaz
}
while ( výraz);

Podmienený príkaz

Podobným príkazom ako je if...else je takzvaný ternárny operátor (podmienený príkaz) (? :) . Používa sa väčšinou, ak sú iba dve možnosti výsledku. Napríklad "áno" "nie". Funkciu má v podstate tú istú ako if, avšak výhodou je skrátenie zápisu. Syntax vyzerá takto:

podmienka? splnená:nesplnená 

7.príklad:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    class Priklad_Pod_Prikaz
    {
        static void Main()
        {
            int i = 1;
            int j = 2;
            string s;
            s = (i == j ? "ano" : "nie");
            /* Otazka: Rovná sa i premennej j? Ak áno, uloží
            sa do s áno. Ak nie, uloží sa do s nie.*/
            Console.Write(s + " ");
            int x =10;
            x *= (i < j ? i : j);
            /* Otázka: Je i menšie ako j? Ak áno, vynásob
            premennú x i. Ak nie, vynásob x premennou j*/
            Console.Write(x);

            Console.ReadLine();
        }
    }
}

Switch :

 
  switch (i)
          {
          case 1:
                príkaz
                break;
          case 2:
                príkaz
                break;
          default: 
                príkaz
                break;
          }

Cyklus foreach:

sa využije najme pri poliach. Pomocou tohto cyklu sa môže prechádzať cez všetky prvky poľa.

8.príklad:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    using System;
    class Priklad_foreach
    {
        static void Main()
        {
            int[] i = { 0, 1, 2, 3, 4 };
            foreach (int j in i)
            {
                Console.Write(j + 1 + " ");
            }

            Console.ReadLine();
        }
    }
}

goto :

Príkaz goto umožňuje skočiť na určený riadok programu a preskočiť tak niektoré riadky programu. To znamená, že v prípade ak sa dosiahne nejaká hodnota napríklad v premennej, tak sa cyklus ukončí a skočí sa na označený riadok v ktorom program pokračuje.

9.príklad:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
   
    class Priklad_goto
    {
        static void Main()
        {
            for (int i = 1; i < 10; i++)
            {
                if (i == 5) goto skok;/*za goto nasleduje nazov riadku
                                       * na ktory chceme skocit*/
                Console.Write(i + " ");
            }
            Console.WriteLine("Toto sa nevypise");//preskoci sa!!!
           skok: Console.WriteLine("koniec");


           Console.ReadLine();
        }
    } 
}

continue :

Príkaz continue je dosť podobný ako príkaz break, ale v jeho prípade dôjde iba k ukončeniu aktuálneho priebehu cyklu, a riadenie programu sa vráti späť na začiatok cyklu.

10.príklad:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
   
    class Priklad_continue
    {
        static void Main()
        {
            for (int i = 1; i < 10; i++)
            {
                Console.Write(i + " ");
                if (i == 5) continue;
                Console.Write(i + " ");
            }
            Console.ReadLine();
        }
    }  
}

Object

11.príklad:

    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            object o = new object();
            Console.WriteLine(o.ToString());
            Console.ReadLine();

            object o1 = new object();
            object o2 = new object();
            if (object.Equals(o1, o2))
                Console.WriteLine("Referencie sú zhodné.");
            else
                Console.WriteLine("Referencie nie sú zhodné.");
            Console.ReadLine();
        }
    }
}
       

Polia

 
string[] s = { "abc", "def", "ghi", "jkl" }; 
bool[] b = new bool[2]
int[] i;  i = new int[5];
string[,] pole = { { "peter", "zahorak" }, { "juraj", "bobak" } };
int[,] p = new int[r, s];
 

Trieda

Trieda je používateľsky definovaný odkazový dátový typ a obsahuje :

 
     class MenoTriedy 
      {
          prikazy
      }
  
  
 
     class Osoba
    {
        private string Meno;
        private int Vek;
        
        
        public void SetMeno(string meno)
        {
            Meno = meno;
        }
        public string GetMeno()
        {
            return Meno;
        }
        public void SetVek(int vek)
        {
            Vek = vek;
        }
        public int GetVek()
        {
            return Vek;
        }
    }

  
  

Inštancia triedy:


 
     static void Main(string[] args)
    {
        Osoba student = new Osoba();
        
        student.SetMeno("Peter");
        student.SetVek(24);
        
        Console.WriteLine(student.GetMeno()); 
        Console.WriteLine(student.GetVek());
        
        Console.ReadLine();
    }

Konštruktor:

 
     class Osoba
    {
        private string Meno;
        private int Vek;
        
        public Osoba(string meno, int vek)
        {
          Meno = meno;
          Vek = vek;
        }
        
        public Osoba(string meno)
        {
          Meno = meno;
        
        }
    }

  
  

12.príklad:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Osoba
    {

        private string Meno;
        private int Vek;
        
        public Osoba(string meno, int vek)
        {
            Meno = meno;
            Vek = vek;
        }

        public Osoba(string meno)
        {
            Meno = meno;

        }

        public void SetMeno(string meno)
        {
            Meno = meno;
        }
        public string GetMeno()
        {
            return Meno;
        }
        public void SetVek(int vek)
        {
            Vek = vek;
        }
        public int GetVek()
        {
            return Vek;
        }


        static void Main(string[] args)
        {
            Osoba student1 = new Osoba("peter",24);
            Osoba student2 = new Osoba("juraj");

            Console.WriteLine(student1.GetMeno());
            Console.WriteLine(student1.GetVek());

            Console.WriteLine(student2.GetMeno());
            Console.WriteLine(student2.GetVek());

            Console.ReadLine();
        }
    }
}

Finalizér:

 
     ~T()    // T je názov triedy
       {
           // Telo finalizéra
       }
  
 
     class Osoba
    {
        private string Meno;
        private int Vek;
        
        public Osoba(string meno, int vek)
        {
          Meno = meno;
          Vek = vek;
        }
        
        public Osoba(string meno)
        {
          Meno = meno;      
        }
        
      ~Osoba() 
        {
          Console.WriteLine("Bol aktivovaný finalizér inštancie.");
        }

    }
  

Prístup ku členom triedy:

Dedičnosť

 
     class A
      {
          // Telo bázovej triedy.
      }
      
      class B : A
      {
          // Telo odvodenej triedy.
      }

  

Polymorfizmus

13.príklad:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{


    class Auto
    {

        string model;
        int cena;
        string farba;

        public Auto(string model, int cena, string farba)
        {
            this.model = model;
            this.cena = cena;
            this.farba = farba;
        }

        public virtual string KonfAuto()
        {
            string auto;
            auto = "Model: " + model + "\n" + "Cena: " + cena + "\n" + "\n" + "Farba: " + farba + "\n";
            return auto;
        }
    }

    class Car : Auto
    {
        private bool turbo;
        public Car(string model, int cena, string farba):base(model,cena,farba)
            
        {
            turbo = true;
        }
        public override string KonfAuto()
        {
            string Auto;
            Auto = base.KonfAuto();
            Auto += "   "+ turbo+ "   ";
           
            return Auto;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car a = new Car("a", 11, "biela");
            Console.WriteLine(a.KonfAuto());

            Console.ReadLine();
        }
    }
}

using System.Net;

14.príklad:

  • http://en.csharp-online.net/IP_Address
  •  
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
     using System.Net;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                Console.Write("Zadajte adresu cieľa (napr. www.shmu.sk) : ");
                string hostName = Console.ReadLine();
                try
                {
                    //vyuzitie systemu DNS pre ziskavanie IP adresy podľa názvu
                    IPHostEntry host = Dns.Resolve(hostName);
                    IPAddress[] addressList = host.AddressList;
                    foreach (IPAddress address in addressList)
                    {
                        Console.WriteLine(address.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
    
                Console.ReadLine(); Console.ReadLine();
    
            }
        }
    }
    
    
    

    15.príklad:

     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Net;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
              Console.Write("Zadajte IP adresu (napr. (81.89.48.15) : ");
    
                try
                {
                    string addressString = Console.ReadLine();
                    IPAddress address = IPAddress.Parse(addressString);
                    Console.WriteLine(address.AddressFamily);
                    Console.WriteLine(address.ToString());
                    Console.WriteLine(IPAddress.IsLoopback(address));
                }
                catch (FormatException)
                {
                    Console.WriteLine("Zadaná adresa nemá správny formát");
                }
    
                Console.ReadLine(); Console.ReadLine();
    
            }
        }
    }
    
    

    16.príklad:

  • http://dotnetperls.com/uri
  •  
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Net;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
    
                Uri uri = new Uri("http://s.ics.upjs.sk/~zahorak/SPS1.html");
      
                 Console.WriteLine("AbsolutePath = {0}", uri.AbsolutePath);
                Console.WriteLine("AbsoluteUri = {0}", uri.AbsoluteUri);
                Console.WriteLine("Authority = {0}", uri.Authority);
                Console.WriteLine("DnsSafeHost = {0}", uri.DnsSafeHost);
                Console.WriteLine("Fragment = {0}", uri.Fragment);
                Console.WriteLine("Host = {0}", uri.Host);
                Console.WriteLine("HostNameType = {0}", uri.HostNameType);
                Console.WriteLine("IsAbsoluteUri = {0}", uri.IsAbsoluteUri);
                Console.WriteLine("IsDefaultPort = {0}", uri.IsDefaultPort);
                Console.WriteLine("IsFile = {0}", uri.IsFile);
                Console.WriteLine("IsLoopback = {0}", uri.IsLoopback);
                Console.WriteLine("IsUnc = {0}", uri.IsUnc);
                Console.WriteLine("LocalPath = {0}", uri.LocalPath);
                Console.WriteLine("OriginalString = {0}", uri.OriginalString);
                Console.WriteLine("PathAndQuery = {0}", uri.PathAndQuery);
                Console.WriteLine("Port = {0}", uri.Port);
                Console.WriteLine("Query = {0}", uri.Query);
                Console.WriteLine("Scheme = {0}", uri.Scheme);
                Console.WriteLine("Segments = {0}", string.Join(",", uri.Segments));
                Console.WriteLine("UserEscaped = {0}", uri.UserEscaped);
                Console.WriteLine("UserInfo = {0}", uri.UserInfo);
                Console.WriteLine(new string('-', 40));
    
    
    
                Console.ReadLine(); Console.ReadLine();
    
            }
        }
    }