class SuperHeroe
{
public string? Nombre;
public string? ColorTraje;
public bool UsaCapa;
public string? UsaMascara;
public List<string>? SuperPoderes;
}
Introducción
Fundamentos de Programación Orientada a Objetos con C#
Prerequisitos
¿Que es la programación orientada a objetos (POO)?
Creando tu primera clase y objeto
Concepto de clases y objetos
Creando clases y propiedades
Creando clases complejas
Trabajando con clases
Constructor y datos iniciales en una clase
Métodos dentro de una clase
Tipos registro y estructura
Modificadores de acceso
Conceptos clave en POO
Encapsulamiento
¿Que es herencia?
Usando herencia en C#
Abstracción
Polimorfismo
Trabajando con interfaces
¿Que es una interfaz?
Usando interfaces
Interfaces vs Clases abstractas
You don't have access to this class
Keep learning! Join and start boosting your career
In object-oriented programming, classes and objects are essential concepts. Mastering their use in C# allows not only to improve code clarity, but also to optimize its reusability and efficiency. But what makes these elements fundamental? Discover how classes act as basic templates for creating objects in the C# world and how understanding their components can elevate your programming skills to the next level.
Classes have two main components:
Properties: These represent the characteristics of the object. For example, when working with an object that represents a bird, properties might include color, species, size, etc.
Methods: These are functions that define the behavior of the object. These methods can vary from something as simple as changing a color to more complex actions such as executing specific commands.
These components allow us to structure classes that can be as easy or complex as necessary, and a good structure facilitates their reuse in application development. By clearly defining the properties and methods of a class, consistent behavior of objects derived from that class is ensured.
Classes are like molds or templates, and from them we derive objects, which are instances of classes. Objects maintain a direct reference to the class that gives them origin, which implies that they contain the characteristics defined in the class, but with values that can be unique for each object. This allows having multiple objects with similar characteristics, but adaptable to specific needs.
Imagine a factory that mass produces products; the classes would be the blueprints and each product would be a unique object based on those blueprints. For example, in a C# context, an object may have properties with specific values such as a "blue" color or a "medium" size.
To create a proper class, it is crucial to analyze the properties and behaviors of objects in their actual context. Let's look at the example of a bird:
For example, two birds may share characteristics such as having wings or a beak, but vary in color or the ability to fly. These shared properties and variables help structure the class efficiently.
Object-oriented programming is not restricted to physical or tangible objects. It is also possible to represent abstract or imaginary entities. For example:
This approach allows for a richer and more versatile representation of concepts in software development. It invites you to experiment and challenge your imagination by emulating these abstract constructs in code form.
As you master these concepts, you will notice how your C# skills improve. Don't forget to share your creations and trials with the community to enrich the collective knowledge - collaborative learning is the key to programming success!
Contributions 79
Questions 1
class SuperHeroe
{
public string? Nombre;
public string? ColorTraje;
public bool UsaCapa;
public string? UsaMascara;
public List<string>? SuperPoderes;
}
Aqui mi aporte de un objeto abstracto
Alma Jp = new Alma();
Jp.pureza = 80.85d;
Jp.Esbuena = true;
Jp.Creencias = true;
Jp.Corompida = false;
class Alma
{
public double pureza;
public bool Esbuena;
public bool Creencias;
public bool Corompida;
}
Les comparto mi ejemplo que desarrollé.
MythicalCreature mythic = new MythicalCreature();
mythic.name = "Loki";
mythic.power = "trick";
mythic.type = "nordic";
class MythicalCreature{
public string name;
public string power;
public string birthplace;
public string type;
public int age;
public double height;
public bool isEvil;
}
Hola! comparto mi ejemplo.
class Princesa
{
public string Nombre;
public int Edad;
public string NombreReino;
public bool TienePoderes;
public bool EsTerrestre;
public string Ubicacion;
};
class Inversiones
{
public string Plataforma;
public string Activo;
public string TipoActivo;
public double Cant;
public double Precio;
public bool EnDolares;
public string FechaInversion;
public string FechaEstmVenta;
public string Riesgo;
}
Inversiones MeliIOL5-10000.Plataforma = "IOL";
Inversiones MeliIOL5-10000.Activo= "MELI";
Inversiones MeliIOL5-10000.Cant = 5;
Inversiones MeliIOL5-10000.Precio = 10000;
Danza danza1 = new Danza();
danza1.nombre = "Marinera";
danza1.partes = 4;
danza1.genero = "Tipica";
class Danza
{
public string nombre;
public int partes;
public string genero;
}
Este video igual solo se escucha del lado izquierdo.
Concepto de Clase * Elemento principal en POO * Se basa en propiedades que representan las características del objeto y métodos que definen el comportamiento. * Se pueden definir como la plantilla base para Crear los objetos.
DiosGriego zeus = new DiosGriego();
zeus._Name = "Zeus";
zeus._Power = "All power";
zeus._Age = "Older than genesis";
class DiosGriego
{
public string _Name { get; set; }
public string _Power { get; set; }
public string _Age { get; set; }
}
DiosGriego zeus = new DiosGriego();
zeus._Name = "Zeus";
zeus._Power = "All power";
zeus._Age = "Older than genesis";
class DiosGriego
{
public string _Name { get; set; }
public string _Power { get; set; }
public string _Age { get; set; }
}
Apuntador apuntadorPlatzi = new Apuntador();
Apuntador apuntadorPlatzi2 = new Apuntador();
apuntadorPlatzi.Color = “Negro”;
apuntadorPlatzi2.Color = “blanco”;
class Apuntador
{
public string Color;
public double Largo;
public short NumeroDeBotones;
public bool TienesStickers;
}
class Hero
{
public string nombre;
public string description;
public int age;
public int enemigos;
}
using System;
class heroeDota2
{
string Nombre;
string tipoDeHeroe;
int nivelHeroe;
int cantidadOro;
float cantidadFuerza;
float cantidadAgilidad;
float cantidadInteligencia;
float cantidadAtaque;
float cantidadArmadura;
string[] items = new string[6];
// Constructor
public heroeDota2(string nombre, string tipo, int nivel, int oro, float fuerza, float agilidad, float inteligencia, float ataque, float armadura)
{
Nombre = nombre;
tipoDeHeroe = tipo;
nivelHeroe = nivel;
cantidadOro = oro;
cantidadFuerza = fuerza;
cantidadAgilidad = agilidad;
cantidadInteligencia = inteligencia;
cantidadAtaque = ataque;
cantidadArmadura = armadura;
}
// Método para agregar un item al héroe
public void AgregarItem(string item)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i] == null)
{
items[i] = item;
break;
}
}
}
}
Mi aporte, esta vez acerca de un videojego conocido.
StarcraftAirUnit wraith = new StarcraftAirUnit();
wraith.Race = "Terran";
wraith.LifePoints = 120;
wraith.GroundDamage = 8;
wraith.AirDamage = 20;
wraith.UnitSpeed = 4.963;
class StarcraftAirUnit
{
public string Race;
public short LifePoints;
public short GroundDamage;
public short AirDamage;
public double UnitSpeed;
}
class automovil {
public string Marca;
public string Modelo;
public datetime año;
public bool TipoVehiculo;
public short NumeroDePuertas
}
class Proyecto {
public string Nombre;
public string FechaInicio;
public string FechaFin;
public string Tipo;
public int NumParticipantes;
}
ritmomusical ritmo = new ritmomusical();
ritmomusical largo = new ritmomusical();
ritmomusical instru = new ritmomusical();
ritmomusical lyris = new ritmomusical();
ritmomusical sample = new ritmomusical();
ritmo.Genero = "Dembow";
largo.duracion = 2.30;
instru.instrumentos = "Piano, guittara y conga";
lyris.nombre = "Boy boy";
sample.samples = false;
class ritmomusical
{
public string Genero;
public double duracion;
public string instrumentos;
public string nombre;
public bool samples;
}
Ventilador ventiladorHome = new Ventilador();
Ventilador ventiladorHome2 = new Ventilador();
ventiladorHome.Marca = “Samurai”;
ventiladorHome.Modelo = “Silence Pro”;
ventiladorHome.color = “Blanco”;
ventiladorHome.TipoVentilador = " Ventilador de Pared";
ventiladorHome2.Marca = “Altezza”;
ventiladorHome2.Modelo = “Altezza Pro”;
ventiladorHome2.color = “Negro”;
ventiladorHome2.TipoVentilador = “Ventilador con Base”;
class Ventilador
{
public string Marca;
public string Modelo;
public string color;
public string TipoVentilador;
}
Emociones emociones = new Emociones();
emociones.Duracion = “10 minutos”;
emociones.Comportamiento = “sonrie”;
emociones.Tipo = “Alegria”;
emociones.concecuencia = “Inspiracion”;
public class Emociones
{
public string Tipo;
public string Comportamiento;
public string Duracion;
public string concecuencia;
}
Guitar ibanez_AZ10 = new Guitar("orange", "black", 6,22);
var color = ibanez_AZ10.getBodyColor();
Console.WriteLine(color);
class Guitar
{
string bodyColor;
string neckColor;
int stringAmount;
int fretAmount;
string pickUps;
public Guitar(string color, string neckColor, int stringAmount, int fretAmount)
{
bodyColor = color;
this.neckColor = neckColor;
this.stringAmount = stringAmount;
this.fretAmount = fretAmount;
}
public string getBodyColor()
{ return bodyColor; }
}
Want to see more contributions, questions and answers from the community?