.NET y C#

Para veteranos y recien nacidos en el mundo de .NET

Introducción a C#/.NET
SENA

2016

Después de hoy vas a conocer más sobre el lenguaje que los poderes de las siguientes plataformas :

Lenguajes del Core .NET

  • C# (v6.0 - 2015)
    • El propósito general es ser un lenguaje basado en la POO
    • C/C++ - Sintaxis similar
  • Visual Basic .NET (v14.0 - 2015)
    • Propósito General, sucesor a VB
  • F# (v3.1.1 - 2014)
    • Lenguaje funcional
  • Todos son compilados bajo el CIL
    • (Common Intermediate Language)

Historia de C#/.NET

C# 2.0

  • Liberado en Noviembre de 2005
  • Los grandes cambios de paradigma de la versión 1.x, incluyo:
    • ​Generics
    • Iterators
    • Delegates
    • Static Classes
static void Main()
{
    foreach (int number in SomeNumbers())
    {
        Console.Write(number.ToString() + " ");
    }
    // Output: 3 5 8
    Console.ReadKey();
}

public static System.Collections.IEnumerable SomeNumbers()
{
    yield return 3;
    yield return 5;
    yield return 8;
}
//Metodos
public void MostrarMensaje(string mensaje, int cantidadVeces) { ... } 
public string MostrarMensaje(string mensaje) { ... } 

//Declaración de delegados
public delegate void MostrarMensajeDelegado(string mensaje, int cantidadVeces); 

//Instancia de delegados
MostrarMensajeDelegado miDelegado =  
    new MostrarMensajeDelegado(MostrarMensaje); 

//Utilizar delegado
miDelegado("hola mundo", 5); 

C# 3.0

  • Liberado en Noviembre 2007
  • Mejoras clave, incluyendo:
    • ​Implementación de Auto Propiedades
    • Métodos de extensión 
    • Lambdas 

C# 4.0 y C# 5.0

  • Liberado en Noviembre de 2010 y Agosto de 2012
  • C# 4.0 introducción a la programación dinámica:
    • ​Dynamic binding (Dynamic Language Runtime)
  • C# 5.0 Se introdujo principalmente:
    • Async/Await
var personas = (from clientes in db.Clientes
                join tipoCliente in db.TipoClientes
                on clientes.idTipoCliente equals tipoCliente.idTipoCliente
                where clientes.estado = 1
                select new {
                            nombreCompleto = (clientes.nombre + " " + clientes.apellido),
                            tipoCliente = tipoCliente.nombre
                       }
                ).ToList();


//Ahora la variable personas ya tiene dos propiedades llamadas 
//nombreCompleto y tipoCliente las cuales se crearon en tiempo de ejecución

C# 6.0

  • Liberado en Julio de 2015
  • C# 6.0 se introdujeron cambios relevantes:
    • Compilador como un servicio ( Roslyn )
    • MejorasAwait
    • Validador de nulos seguro (objectInstance?.propertyA)
    • Interpolación de cadenas
    • Valores por defecto para objetos

.NET Framework

Arquitectura y funcionamiento

 

(Visualizar el documento en PDF)

y estas...

Empecemos

.NET Package Manager

 

 

Dejemos la tranquilidad, veamos código...

Primeros pasos con C#

C# Tipos Básicos 

Tipos por valor

  • Numerics (Structs)
    • Integer (Int, Long, etc)
    • Floats (Float, Double)
    • Decimal
  • Boolean
  • Character (char)
  • Enumerations
  • Otras estructuras
    • DateTime

Tipos por referencia

  • Objects
    • Base de los tipos por referencia
  • Interfaces
  • Delegates
  • String
    • Igualdad / asignación como un tipo de valor

Clases/Objetos

Introducción

  • C# es un lenguaje basado en POO, todo es un objeto
  • Todo hereda del tipo object type
  • Para instanciar clases se realiza con la palabra reservada new() o new(parametro1, ...)
  • Utiliza la herencia clásica 
  • No soportan multiple herencia

Classes/Objects

Class vs Struct

  • Classes are:
    • Reference types
    • Used for modeling complex behavior
    • Used throughout the framework and in the wild
  • Structures are:
    • Value types
    • Used for modeling simple data structures that typically do not change after assignment
    • Used for the numerics and DateTime in the framework

Classes/Objects

Variables

  • Store values or logic (lambdas)
  • Strongly-typed, but local variable usage of var keyword in a method is allowed through compiler replacement
  • Class variables types
    • Static variables
    • Instance variables

Parameters

  • Value parameters
  • Reference parameters - use with the ref keyword
  • Output parameters - use with the out keyword

Classes/Objects

Access Modifiers

  • Public
  • Protected - containing class or in derived types
  • Internal - in current assembly
  • Private - containing class only

Some Other Modifiers

  • Const - constant (compile-time)
  • Readonly - set once per instance (run-time)
  • Sealed - can not be inherited from
  • Static - member belongs to type itself
  • Abstract - class/members to be defined by derived class
  • Virtual - allows implementation to be overridden

Classes/Objects

Interfaces

  • Contain definitions for a group of related functionalities that a class or struct can implement
  • Contract types that can be used in place of concrete types to allow for flexibility and reusable code
  • A class can implement multiple interfaces for composition

Classes/Objects

Constructors

  • Mainly used types
    • Instance Constructor
    • Private Constructor (commonly for singletons)

 

  • When objects are initialized, the following execute:
    • Base Constructors
    • Derived Constructors
    • Property Initialization

Classes/Objects

Garbage Collection

  • .NET handles garbage collection automatically
  • Exceptions include:
    • File and I/O interactions
    • Database connections
    • Graphics
    • Network sockets
  • These require handling disposal via the IDisposable interface's .Dispose() method
    • Syntactic sugar with using clauses
  • More at: https://msdn.microsoft.com/en-us/library/0xy59wtx(v=vs.110).aspx

Generics

Generics

Overview

  • Allows generalization of functionality
  • Compiler generates code for each of the different type usages of the generalized functionality
    • Using interfaces can allow run-time binding to a specific type
  • Most commonly seen with collections in .NET

Generics

Generic Collections

  • System.Collections.Generic
    • List<T>
    • Dictionary<T1, T2>
    • HashSet<T>
    • Tuple<T1, T2, ...>
    • etc...

Generics

Custom Generics

  • Specify generic type(s) and constraints (if applicable) in method signature
  • Use generic types in place of concrete types or interfaces

Methods

Overview

  • Types of Methods
    • Static methods exist on type itself
      • Can not make use of instance members (fields or methods)
    • Instance methods exist on the instance of the class
      • Can make use of static methods and fields
    • ​Anonymous functions/lambdas
      • ​Can be defined with delegates & Func/Action types

 

  • "Getters"/"Setters" are implemented with C# Properties
  • Extension methods can add functionality to sealed classes

Methods

Method Signature

  • Access Modifier
  • Inheritance-related Modifier (optional)
  • Asynchronous Modifier (optional)
  • Return Type or "void"
  • Generic Types <T1, T2, etc...> (optional)
  • Input Parameters
  • Generic Constraints (optional)

Methods

Lambdas

  • Anonymous functions that can be used to create delegates or expression tree types
  • Heavily used in LINQ due to code conciseness
  • Can be implemented within a closure

Methods

Extension Methods

  • Special static methods that appear to be on the class
  • Extension methods are defined on public static classes
  • Signature of an extension method is the following:
    • public static int WordCount(this String str)
  • At compiler converts to a call to the static method

Conditionals and Loops

Conditionals Overview

  • Pretty standard and similar to Java
    • Conditionals: If/Switch
  • Switch
    • Doesn't fall through
    • Can have multiple cases share same branch
  • Ternary operator
  • Newer versions of .NET have:
    • Null coalesce (e.g. possiblyNullValue ?? fallbackValue)
    • Null safe navigation (e.g. possiblyNullValue?.propA)

Conditionals and Loops

Looping Overview

  • Pretty standard and similar to Java
    • Loops: For/Do-while/While
    • For IEnumerables, can use foreach
  • break keyword breaks out of a loop
  • continue keyword jumps to the next iteration

Reflection

Overview

  • Allows the C# runtime to dynamically execute code through self-inspection of assemblies, modules, & types

 

  • Reflection drives much of the behavior within of C#/.NET
  • Used heavily by IoC container implementations
  • Direct usage of reflection is best avoided when possible
    • Large performance hit
    • Lose benefit of strong typing
    • Can cause vague exceptions and code execution paths

Attributes

Overview

  • Used to attach declarative information to any type
  • Comparable to Java Annotations
  • Uses reflection under the covers
  • Used heavily in:
    • WCF (.NET SOAP/RPC solution, serialization hints)
    • ASP.NET (.NET web platform - HTTP verb/method map)
    • .NET Aspect-Oriented Programming solutions
  • Are inherited in child classes

LINQ

Overview

  • Language-Integrated Query
  • Heavily used by Entity Framework and other .NET ORMs
  • As the name implies it's a querying language for collections that derive from IEnumerable and IQueryable
    • ​IEnumerable generally are in-memory collections
    • IQueryable represent external data collections
  • Can use for sorting, filtering, map/reduce actions
  • Functional like programming
  • Generally deferred executions with both collection types
    • Exceptions: .ToList(), .First(), .Single(), .Take(), etc.
    • These functions force evaluation

LINQ

Overview (con't)

  • SQL-like syntax, but usually ends with the SELECT logic
  • Two forms
    • Query Comprehension
      • from num in numbers
        where num % 2 == 0
        orderby num
        select num;
    • Fluent Interface
      • collectionToQuery.Where(...).Select(...)

Learning Resources

Libraries

Popular .NET Libraries by Microsoft

Popular 3rd-Party .NET Libraries

Conclusion

  • .NET and C# are awesome

 

  • Heavily used in mobile/cross-platform development

 

  • Relatively quick to pick up for a Java developer

 

  • New language features are always being added
    • Compiler and core libraries are open source

Thanks!

Introducción a C#/.NET

By Yhoan Andres Galeano Urrea