my_int = 8 my_decimal = 8.5 my_string = "electron" puts "My int is: #{my_int}" puts "My float is: #{my_decimal}" puts "My string is: #{my_string}"
using System; public class Program { public static void Main() { int myInt = 8; double myDecimal = 8.5; string myString = "electron"; Console.WriteLine("My int is: {0}", myInt); Console.WriteLine("My float is: {0}", myDecimal); Console.WriteLine("My string is: {0}", myString); } }
Console.WriteLine()
is called, implying that the values will be output to the console. There are also several lines in which interpolation appears to be used to compose messages. Conceptually, there is nothing particularly surprising here - assignment, interpolation, output to the console, all these operations are already known to you for working with Ruby.Main()
method? What are these keywords int
, double
and string
? This is where the training begins. You already understand in general what is happening here (assignment, interpolation, output), now is the time to move on to the details:Main()
: Having a little insight into the situation, we find out that the Main()
method is the input point from which the program starts. Now we know that in all C # programs we need the Main () method.int
means an integer variable, double
is a double-precision floating-point number, and string
is a string variable. Almost immediately, you will guess that in C #, unlike Ruby, static typing of variables is required, since variables for different data types are declared differently. After reading the documentation, you will understand how different.Console.WriteLine()
: Finally, when you run the program, you will see that Console.WriteLine()
displays the values in the console. From Ruby, you know that puts
is a method of the global $stdout
object, and, referring to the documentation for Console.WriteLine()
, you will learn that the Console
is a class from the System
namespace, and WriteLine()
is the method defined in this classroom. This is not only very similar to puts
, but also suggests that C #, like Ruby, is an object-oriented language. Here you have one more mental model that will help to trace the new parallels. particles = ["electron", "proton", "neturon"] particles.push("muon") particles.push("photon") particles.each do |particle| puts particle end
particles
, which will have several lines, and then use Array#push
to add a few more lines to it, and Array#each
to iterate through the array and output each individual line to the console. But how to do the same in C #? A little googling, we learn that there are typed arrays in C # (typing should no longer surprise you, considering what you learned earlier), and also there is the SetValue method, which slightly resembles push
, but takes the value and position in the index as parameters. In this case, the first attempt to rewrite Ruby code in C # might look like this: using System; using System.Collections.Generic; public class Program { public static void Main() { string[] particles = new string[] { "electron", "proton", "neturon" }; particles.SetValue("muon", 3); // ( 11): particles.SetValue("photon", 4); foreach (string particle in particles) { Console.WriteLine(particle); } } }
Run-time exception
runtime Run-time exception
when you try to use SetValue
to add a new value to the array. We look at the documentation again and find out that the arrays in C # are not dynamic, and must be initialized either with all the values at once, or with an indication of the length. Again, trying to reproduce the Ruby code, we take this into account and get the following option: using System; using System.Collections.Generic; public class Program { public static void Main() { string[] particles = new string[] { "electron", "proton", "neturon", null, null }; particles.SetValue("muon", 3); particles.SetValue("photon", 4); foreach (string particle in particles) { Console.WriteLine(particle); } } }
using System; using System.Collections.Generic; public class Program { public static void Main() { List<String> particles = new List<String>(); particles.Add("electron"); particles.Add("proton"); particles.Add("neutron"); particles.Add("muon"); particles.Add("photon"); foreach (string particle in particles) { Console.WriteLine(particle); } } }
List
data structure that allows you to dynamically collect values. In this case, we actually reproduce the original Ruby code in C #, but, more importantly, here we can appreciate the key difference between the two languages. Although, in both languages the term “array” is used and it may seem that these arrays are one and the same, in practice they are quite different. Here you have one more thing that helps to expand the mental model, to more fully understand what an “array” is and how it works. In C #, an array as a data structure may or may not be suitable in situations where you would use arrays in Ruby; Speech about situations where dynamic resizing of an array is critical. Now you have to take care of this in advance and think through your code accordingly.System.Console.WriteLine()
, with which we performed the action. It is logical to assume that C #, like other object-oriented languages, has a mechanism for defining a class and instantiating objects from it. This is a basic principle of object-oriented programming, so there is little doubt that our assumption is correct. First, let's look at how this operation might look like in the Ruby language we know. class Element attr_accessor :name, :symbol, :number def initialize(name, symbol, number) self.name = name self.symbol = symbol self.number = number end def describe puts "#{self.name} (#{self.symbol}) has atomic number #{self.number}." end end hydrogen = Element.new("Hydrogen", "H", 1) hydrogen.describe
Element
class, which has a constructor method to accept values and assign them to instantiated objects, a set of access methods for setting and retrieving values, and an instance method for outputting these values. In this case, the key concepts are the idea of a class, the idea of a constructor method, the idea of getters / setters, and the idea of an instance method. Returning to our ideas about what can be done in object-oriented languages, consider how to do the same in C #. using System; public class Program { public static void Main() { Element hydrogen = new Element("Hydrogen", "H", 1); hydrogen.Describe(); } public class Element { public string Name { get; set; } public string Symbol { get; set; } public int Number { get; set; } public Element(string name, string symbol, int number) { this.Name = name; this.Symbol = symbol; this.Number = number; } public void Describe() { Console.WriteLine ( "{0} ({1}) has atomic number {2}.", this.Name, this.Symbol, this.Number ); } } }
this
, whereas in Ruby we use self
for this. The C # version is typed both at the method level and at the parameter level, but not in Ruby. However, at the level of key principles, both fragments are almost identical. class Element attr_accessor :name, :symbol, :number def initialize(name, symbol, number) self.name = name self.symbol = symbol self.number = number end def describe puts "#{self.name} (#{self.symbol}) has atomic number #{self.number}." end end class NobleGas < Element attr_accessor :category, :type, :reactivity def initialize(name, symbol, number) super(name, symbol, number) self.category = "gas" self.type = "noble gas" self.reactivity = "low" end def describe puts "#{self.name} (#{self.symbol}; #{self.number}) is a #{self.category} " + "of type #{self.type}. It has #{self.reactivity} reactivity." end end argon = NobleGas.new("Argon", "Ar", 18) argon.describe
NobleGas
subclass that inherits from our Element
class; its constructor uses the super keyword, which extends the constructor of the parent class and then overrides the instance method describe
, to define a new behavior. The same can be done in C #, but with a different syntax: using System; public class Program { public static void Main() { NobleGas argon = new NobleGas("Argon", "Ar", 18); argon.Describe(); } public class Element { public string Name { get; set; } public string Symbol { get; set; } public int Number { get; set; } public Element(string name, string symbol, int number) { this.Name = name; this.Symbol = symbol; this.Number = number; } public virtual void Describe() { Console.WriteLine ( "{0} ({1}) has atomic number {2}.", this.Name, this.Symbol, this.Number ); } } public class NobleGas : Element { public string Category { get; set; } public string Type { get; set; } public string Reactivity { get; set; } public NobleGas(string name, string symbol, int number) : base(name, symbol, number) { this.Category = "gas"; this.Type = "noble gas"; this.Reactivity = "low"; } public override void Describe() { Console.WriteLine ( "{0} ({1}; {2}) is a {3} of type {4}. It has {5} reactivity.", this.Name, this.Symbol, this.Number, this.Category, this.Type, this.Reactivity ); } } }
Source: https://habr.com/ru/post/422869/
All Articles