Menú de navegaciónMenú
Categorías

La mejor forma de Aprender Programación online y en español www.campusmvp.es

?id=39b35cbc-1480-444c-80d9-d06bba9ba129

Pregunta-Trampa: El lenguaje C# y la plataforma .NET no son lo mismo

faq

Hace poco un alumno me hizo una consulta acerca de una pregunta que le habían planteado en un ejercicio académico. Considero interesante reproducirla, porque nos permite clarificar y distinguir lo que es el propio lenguaje C# y las librerías que habitualmente utilizamos desde C#. (Por cierto, si necesitas aprender bien a desarrollar con C# y .NET, échale un vistazo a este curso.)

Enunciado

Indicar cómo se puede escribir un texto dentro de un archivo en disco utilizando únicamente el lenguaje C#. Se darán puntos extra a quien responda en una sola línea.

Respuesta breve

Es imposible.

Respuesta larga

Se trata de una pregunta-trampa. El lenguaje C# no define instrucciones de entrada/salida. Escribir un archivo en disco es una operación de salida. En consecuencia, no se puede hacer utilizando únicamente C#.

Para escribir el fichero, será necesario recurrir a alguna biblioteca externa que sea capaz de realizar las operaciones de entrada/salida. Bajo circunstancias normales, típicamente se utilizarán las bibliotecas de la Framework Class Library (FCL) incluidas en el Framework de .Net. Para escribir en un archivo en disco, usaremos las clases contenidas en el espacio de nombres System.IO dentro de la biblioteca System.DLL.

Para ello, será necesario añadir una referencia a esa biblioteca . Si el programa se genera con Visual Studio, de manera predeterminada se añade automáticamente la referencia a System.DLL. Lo mismo sucede si compilamos desde línea de comandos con CSC.EXE.

Una vez referenciada la biblioteca , es muy sencillo escribir el texto en el archivo:

System.IO.File.WriteAllText(@”c:\ruta\nombre.txt”, “Contenido”);

Nótese que hemos resuelto en una sola línea el problema inicialmente planteado... pero no lo hemos hecho utilizando únicamente C#. Aunque nosotros sólo hemos tecleado código en C#, nos estamos apoyando en una biblioteca externa, que por dentro utiliza (directa o indirectamente) un bloque de código que no está escrito en C#.

Enseñanza

Con frecuencia alguien plantea en los foros públicos una consulta sobre programación insistiendo en que tiene que hacerlo solo con C#. En general, lo que en realidad quieren decir es que desean hacerlo solo con las librerías del Framework, sin adquirir ninguna biblioteca de terceras partes. Pero recordemos que esas librerías no forman parte del lenguaje C#, simplemente suelen usarse conjuntamente con C#, pero son independientes del lenguaje.

Una cosa es el lenguaje (C#, Visual Basic o cualquiera de los muchos disponibles en .NET) y otra muy diferente es la plataforma .NET. Es necesario tenerlo muy claro.

Nota: Autor de la imagen de la cabecera photosteve101(www.planetofsuccess.com/blog/ ). Imagen usada bajo licencia CC

Fecha de publicación:
Alberto Población Alberto es MVP de C#, y lleva varias décadas desarrollando software. Cuenta entre otras con las certificaciones MCSE, MCDBA, MCITP, MCSD, MCPD. En la actualidad trabaja como consultor independiente dedicándose también a la formación. Es instructor certificado por Microsoft. Ver todos los posts de Alberto Población
Archivado en: Lenguajes y plataformas

Boletín campusMVP.es

Solo cosas útiles. Una vez al mes.

🚀 Únete a miles de desarrolladores

DATE DE ALTA

x No me interesa | x Ya soy suscriptor

La mejor formación online para desarrolladores como tú

Comentarios (3) -

Luis Guzman
Luis Guzman

Hola. Sr. ALberto buscando ayuda en la red de como encontrar a quien me eayude a encontrar el problema que tengo e encontrado este sitio Docente y la posibilidad de preguntar a alguien y aunque no pertenezco a ese Institucion quizas me puedan brindar ayuda a la larga es tema posible de uilizar como un problema Docente.

Miu Probelma es utilizar al algoritmo de Prim usando  C# VS2017 y buscando encontre en el sitio www.GeeksforGeeks.com una solucion pero tengo mis dudas de porque no corre tanto el problema de ejemplo como otro en el cual yole entre una matriz de Adyacencia Ok y tampoco corre. Adujunto toda la informacion psoible del sitio.. Expecto la parte descriptiva del correr paso apaso el algoritmo que no se reprersenta en la copia que le envio..

Gracias Milpor su tiempo.

Luis  E. Guzman


Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5



We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s algorithm, Prim’s algorithm is also a Greedy algorithm. It starts with an empty spanning tree. The idea is to maintain two sets of vertices. The first set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every step, it considers all the edges that connect the two sets, and picks the minimum weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing MST.
A group of edges that connects two set of vertices in a graph is called cut in graph theory. So, at every step of Prim’s algorithm, we find a cut (of two sets, one contains the vertices already included in MST and other contains rest of the verices), pick the minimum weight edge from the cut and include this vertex to MST Set (the set that contains already included vertices).

How does Prim’s Algorithm Work? The idea behind Prim’s algorithm is simple, a spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.

Algorithm
1) Create a set mstSet that keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign key value as 0 for the first vertex so that it is picked first.
3) While mstSet doesn’t include all vertices
….a) Pick a vertex u which is not there in mstSet and has minimum key value.
….b) Include u to mstSet.
….c) Update key value of all adjacent vertices of u. To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous key value of v, update the key value as weight of u-v

The idea of using key values is to pick the minimum weight edge from cut. The key values are used only for vertices which are not yet included in MST, the key value for these vertices indicate the minimum weight edges connecting them to the set of vertices included in MST.


Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

How to implement the above algorithm?
We use a boolean array mstSet[] to represent the set of vertices included in MST. If a value mstSet[v] is true, then vertex v is included in MST, otherwise not. Array key[] is used to store key values of all vertices. Another array parent[] to store indexes of parent nodes in MST. The parent array is the output array which is used to show the constructed MST.
      

// A C / C++ program for Prim's Minimum  
// Spanning Tree (MST) algorithm. The program is  
// for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
#include<stdbool.h>
// Number of vertices in the graph
#define V 5
  
// A utility function to find the vertex with  
// minimum key value, from the set of vertices  
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
  
for (int v = 0; v < V; v++)
    if (mstSet[v] == false && key[v] < min)
        min = key[v], min_index = v;
  
return min_index;
}
  
// A utility function to print the  
// constructed MST stored in parent[]
int printMST(int parent[], int n, int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
    printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
  
// Function to construct and print MST for  
// a graph represented using adjacency  
// matrix representation
void primMST(int graph[V][V])
{
    // Array to store constructed MST
    int parent[V];  
    // Key values used to pick minimum weight edge in cut
    int key[V];  
    // To represent set of vertices not yet included in MST
    bool mstSet[V];  
  
    // Initialize all keys as INFINITE
    for (int i = 0; i < V; i++)
        key[i] = INT_MAX, mstSet[i] = false;
  
    // Always include first 1st vertex in MST.
    // Make key 0 so that this vertex is picked as first vertex.
    key[0] = 0;      
    parent[0] = -1; // First node is always root of MST  
  
    // The MST will have V vertices
    for (int count = 0; count < V-1; count++)
    {
        // Pick the minimum key vertex from the  
        // set of vertices not yet included in MST
        int u = minKey(key, mstSet);
  
        // Add the picked vertex to the MST Set
        mstSet[u] = true;
  
        // Update key value and parent index of  
        // the adjacent vertices of the picked vertex.  
        // Consider only those vertices which are not  
        // yet included in MST
        for (int v = 0; v < V; v++)
  
        // graph[u][v] is non zero only for adjacent vertices of m
        // mstSet[v] is false for vertices not yet included in MST
        // Update the key only if graph[u][v] is smaller than key[v]
        if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
            parent[v] = u, key[v] = graph[u][v];
    }
  
    // print the constructed MST
    printMST(parent, V, graph);
}
  
  
// driver program to test above function
int main()
{
/* Let us create the following graph
        2 3
    (0)--(1)--(2)
    | / \ |
    6| 8/ \5 |7
    | /     \ |
    (3)-------(4)
            9         */
int graph[V][V] = {{0, 2, 0, 6, 0},
                    {2, 0, 3, 8, 5},
                    {0, 3, 0, 0, 7},
                    {6, 8, 0, 0, 9},
                    {0, 5, 7, 9, 0}};
  
    // Print the solution
    primMST(graph);
  
    return 0;
}

Output:
Edge   Weight
0 - 1    2
1 - 2    3
0 - 3    6
1 - 4    5

Time Complexity of the above program is O(V^2). If the input graph is represented using adjacency list, then the time complexity of Prim’s algorithm can be reduced to O(E log V) with the help of binary heap. Please see Prim’s MST for Adjacency List Representation for more details.






Responder

Hola. Y como sabemos o tenemos certeza, de que la biblioteca IO no está escrita en c# puro?
Saludos

Responder

José Manuel Alarcón
José Manuel Alarcón

Hola Gus:

Como has dejado un email falso quizá no llegues a leer esto, pero en cualquier caso lo contestaremos.

Por supuesto que la mayor parte de las clases base de la plataforma están escritas en C#, pero al final la lectura o escritura a disco la tiene que hacer alguna función del sistema operativo. Puedes tener la certeza porque, además de que la plataforma .NET es de código abierto y puedes ver su código fuente, la puedes decompilar también con muchas herramientas. Y en el caso de System.IO.File.WriteAllText, si le vas siguiendo la pista al código al final llegas al método InternalBlockCopy de la clase System.Buffer que es la que se encarga de escribir a disco y que se define así en C# (puedes verlo aquí: referencesource.microsoft.com/.../buffer.cs,636e4f5bf81c5be1):

[MethodImpl(MethodImplOptions.InternalCall)]
[SecuritySafeCritical]
internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes, Array dst, int dstOffsetBytes, int byteCount);

La palabra clave extern indica que este método se delega a un método externo al código C#, que puede ser un código de una DLL del sistema o, como indica en este caso el primer atributo "InternalCall", una llamada a un método interno de la CLR (la biblioteca de tiempo de ejecución de .NET que es específica de cada sistema: echa un vistazo a este artículo: www.campusmvp.es/.../...us-principales-partes.aspx). Esto es código nativo, no escrito en C# ni en ningún lenguaje .NET.

De todos modos, lo que el post trataba de aclarar no es si la mayor parte o no de las bibliotecas base de .NET están escritas en C# o en VB o en otro lenguaje (están en C#, y lo sabemos porque es Open Source, pero eso no es lo importante), sino que hay que distinguir entre lo que es el lenguaje y lo que es la plataforma. Son cosas diferentes que a veces se confunden.

Saludos.

Responder

Agregar comentario

Los datos anteriores se utilizarán exclusivamente para permitirte hacer el comentario y, si lo seleccionas, notificarte de nuevos comentarios en este artículo, pero no se procesarán ni se utilizarán para ningún otro propósito. Lee nuestra política de privacidad.