Vous êtes sur la page 1sur 39

C SHARP

Introduccin a C#

INTRODUCCIN
Lenguaje Nativo de .NET
Sintaxis y estructuracin parecida a C++ Java.

INTRODUCCIN
Caractersticas de C#
Sencillez: C# elimina elementos que otros lenguajes incluyen y que son innecesarios en .NET. Por ejemplo:

Cdigo escrito en C# es autocontenido, es decir, no necesita de ficheros adicionales al propio fuente. Tamao de los tipos de datos bsicos es fijo e independiente del compilador, SO o mquina para quienes se compile. No se incluyen elementos como macros, herencia mltiple o la necesidad de un operador diferente del punto (.) acceder a miembros de espacios de nombres (::)

INTRODUCCIN
Caractersticas de C#:
Modernidad: incorpora en el propio lenguaje elementos que a lo largo de los aos ha ido demostrndose son muy tiles para el desarrollo de aplicaciones: decimal, foreach, string, bool. Orientacin a objetos: Como todo lenguaje de programacin de propsito general actual. Soporta las caractersticas propias del paradigma de POO: encapsulacin, herencia y polimorfismo. Mtodos por defecto sellados y los redefinibles se marcan con el modificador virtual.

AMBIENTE DE DISEO
Menus Solution explorer

Form

Code editor

Toolbar
messages
Properties/events window

AMBIENTE DE DISEO
The Form Controles importantes

Form

Textbox
Button Label

Listbox

AMBIENTE DE DISEO
The Toolbox

AMBIENTE DE DISEO
The Properties / Events window
Por ejemplo, cada control tiene:
Name Position (top and left) Size (height and width) Text Description of property

AMBIENTE DE DISEO
The Properties / Events window
Events happen to controls
Button click KeyPress MouseMove MouseDown

AMBIENTE DE DISEO
Editor de cdigo

MY FIRST PROGRAM
using System;
namespace HolaMundo { public class MyFirstClass { static void Main() {

Console.WriteLine("Hello from Wrox.");


Console.ReadLine(); }

}
}

MY FIRST PROGRAM
namespace HolaMundo { public class MyFirstClass { static void Main() {

System.Console.WriteLine("Hello from Wrox.");


System.Console.ReadLine(); }

}
}

MY FIRST PROGRAM
namespace HolaMundo { public class MyFirstClass { static void Main() {

HolaMundo.MyFirstClass

System.Console.WriteLine("Hello from Wrox.");


System.Console.ReadLine(); }

}
}

C#
Comentarios:
// /* */

Modificadores de mtodos: public static

VARIABLES
Declaracin de variables:
datatype identificador Ejemplo:

int i; int x=10, y=12; bool s=true;


Error:
int x=9, bool s=true;

VARIABLES
public static int Main()
{ int d;

Console.WriteLine(d); // ?????
return 0; }

VARIABLES
using System;
namespace HolaMundo { class HelloWorld { static void Main(string[] args) { var nombre = "Bugs Bunny"; var edad = 19; var esConejo = true; Console.WriteLine("nombre es de tipo: " + nombre.GetType()); Console.WriteLine("edad es de tipo: " + edad.GetType()); Console.WriteLine("esConejo es de tipo" + esConejo.GetType()); Console.WriteLine("La edad al cuadrado es: " + edad * edad); Console.ReadLine(); } } }

VARIABLES LOCALES
using System;
namespace HolaMundo { class HelloWorld { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Console.WriteLine(i); } //En este punto, i esta fuera de del ambito //Podemos declarar otra variable i, porque no hay otra for (int i = 9; i >= 0; i--) { Console.WriteLine(i); }//i ya esta fuera del ambito } } }

VARIABLES LOCALES Y GLOBALES


using System;
namespace HolaMundo { class HelloWorld { static int j = 20; public static void Main() { int j = 30; Console.WriteLine(j+20); Console.WriteLine(HelloWorld.j); Console.ReadLine(); } } }

CONSTANTES
El valor no cambia.
const int a = 23;

TIPOS DE DATOSTIPOS VALOR


Enteros
int, long, short. Flotantes
double, float (float m = 15.6f float m = 15.6F)

Decimal
decimal de = 15.4M decimal de = 15.4m

Booleano bool Character char

TIPOS DE DATOSTIPOS REFERENCIA


object
string string(char unCaracter, int numeroRepeticiones) string(char[ ] unArreglo); string(char[ ] unArreglo, int inicio, int tamao)

TIPOS DE DATOSTIPOS REFERENCIA


object
string string str1 = new string('m', 7); char[] myArray = { 'h', 'o', 'l', 'a' }; string str2 = new string(myArray); string str3 = new string(myArray, 1, 2);

string str4 = "Ian es un paquete";


Se puede acceder a los caracteres: Console.WriteLine(str4[2]);

Error: string str5 = new string("Hola mundo");

TIPOS DE DATOSTIPOS REFERENCIA


string
int IndexOf(char carcter) int IndexOf(char carcter, int comienzo) int IndexOf(char carcter, int comienzo, int longitud) string Insert(int comienzo, string unaCadena) string Remove(int comienzo, int numCaracteresRemo) string Replace(string viejo, string nuevo) String ToUpper() String ToLower()

TIPOS DE DATOSTIPOS REFERENCIA


string
StartsWith(string unaCadena) EndsWith(string unaCadena) Substring(int startIndex) ToCharArray Trim TrimEnd TrimStart

TIPOS DE DATOS
int[] unArray;
int[] unArray=new int[5]; int[] miArray = new int[5]{ 2, 5, 12, 56, 3 }; int[] miArray = new int[]{ 2, 5, 12, 56, 3 }; int[] miArray = { 2, 5, 12, 56, 3 }; int[,] otroArray={{3,5,7},{6,89,21},{34,56,7}};

TIPOS DE DATOSTIPOS REFERENCIA


string
int Length, es una propiedad, no mtodo.

FLUJOS DE CONTROLSENTENCIAS CONDICIONALES


Ramificacin de cdigo:
If switch

FLUJOS DE CONTROLSENTENCIAS CONDICIONALES


bool isZero;
if (i == 0) {

isZero = true;
Console.WriteLine("i is Zero"); } else { isZero = false; Console.WriteLine("i is Non-zero"); }

FLUJOS DE CONTROLSENTENCIAS CONDICIONALES


switch (integerA)
{ case 1: Console.WriteLine("integerA =1");

break;
case 2: Console.WriteLine("integerA =2"); break; case 3: Console.WriteLine("integerA =3"); break; default: Console.WriteLine("integerA is not 1,2, or 3"); break; }

LOOPS
for (int i = 0; i < 100; i=i+1) // This is equivalent to
{ Console.WriteLine(i);

for (var i = 0; i < 100; i++) { Console.WriteLine(i); }

LOOPS
while (condition)
{ // Do something.

LOOPS
do
{ //Do something

} while (condition);

LOOPS
Permite recorrer cada elemento de una coleccin.
foreach (int temp in arrayOfInts)//foreach (int temp in arrayOfInts) {

Console.WriteLine(temp);
}

foreach (int temp in arrayOfInts) { temp++; Console.WriteLine(temp); }

JUMP STATEMENTS
int i = 1;
if (i == 1) { Console.WriteLine("Hola");

goto Eti1;
} else { goto Error; } Eti1: Console.WriteLine("Otro hola"); Error: Console.WriteLine("Error");

JUMP STATEMENTS
break
continue return

METHODS
Creacin y uso de mtodos.

EJERCICIO
Comparar dos nmeros e imprimirlos y decir si son iguales, diferentes, si el primero es menor que el segundo, o si es menor igual, o mayor, o mayor igual.
Realizar un programa que indique si una palabra es un palndromo. Imprimir los nmeros nones entre el 1 y 100. Construir una aplicacin que sume dos numero y proporcione el resultado de la siguiente manera: El resultado de la suma de numero1 y numero2 es resultado. Realizar un programa que reciba el nombre de un mes del ao, y como resultado debe proporcionar el nmero de mes correspondiente. Tomar en cuenta el siguiente formato de salida: Nombre del mes es el mes nmero nmero del mes del ao.

Vous aimerez peut-être aussi