@tomislav91
1) koristi StringBuilder, zato sto je string + string i mnogo puta + string jako sporo. Zato sto:
2000 stvari o c# -> string
2) Funkcija, Klasa itd, treba da rade jednu i samo jednu stvar i to najbolje na svetu.
Single responsibility principle
3) TryParse moze da ne uspe :)
4) C# ima String.Empty, System.Environment.NewLine konstante.
5) MultiplicationTable funkcija na bi trebalo da bude u klasi Form1, nego static u klasi MyCustomTableFunctions na primer. Zasto ? Vidi 2), a uz to bice dostupna i na drugim mestima, neces valjda
da radis copy/paste MultiplicationTable u Form2, Form3,... FormN ?
Tako da treba da bude:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace forum
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int input = 0;
if (int.TryParse(txtUserInput.Text, out input))
{
lblResult.Text = MultiplicationTable(input);
}
}
private string MultiplicationTable(int input)
{
StringBuilder result = new StringBuilder();
for (int i = 2; i <= 10; i++)
{
result.AppendFormat("{0} X {1} = {2}", input, i, input * i);
result.AppendLine();
}
return result.ToString();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Ili jos bolje:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace forum
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int input = 0;
if (int.TryParse(txtUserInput.Text, out input))
{
lblResult.Text = MyCustomTableFunctions.MultiplicationTable(input);
}
else
{
lblResult.Text = "I can't parse that thing !";
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
public class MyCustomTableFunctions
{
public static string MultiplicationTable(int input)
{
StringBuilder result = new StringBuilder();
for (int i = 2; i <= 10; i++)
{
result.AppendFormat("{0} X {1} = {2}", input, i, input * i);
result.AppendLine();
}
return result.ToString();
}
}
}
[Ovu poruku je menjao ssi dana 10.10.2014. u 13:08 GMT+1]