Change sprite texture through script

I have a game object with a sprite renderer component. The sprite renderer has not been assigned any sprite through the Inspector.
I have two textures (say img1 and img2) in my Resources folder.
I need to assign one of these textures as my sprite textures during run time.
This is what I tried but doesn’t seem to work :

gameObject.GetComponent<SpriteRenderer> ().sprite = (Sprite)Resources.Load ("img1");

Any suggestions on how can this be done ?

SOLVED !

A small modification made the difference !

gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load("img1", typeof(Sprite)) as Sprite;

You can declare two public Sprite variable and assign in inspector.

public Sprite img1 , img2;

void SetSprite()
{
    gameObject.GetComponent<SpriteRenderer>().sprite = img1;
}
void SetSprite2()
{
    gameObject.GetComponent<SpriteRenderer>().sprite = img2;
}

Hate to say it, but these are horrible solutions. The best suggestion here is to create two Sprite inspector variables and use the one you need at any given time, however, you should also make a SpriteRenderer inspector variable instead of calling GetComponent every time you need to set it.

The worst thing you could do here is use Resources.Load(), because if you put Sprites in the Resources folder, they aren’t packed to an atlas, which ruins the optimization of sprites.

The sprites need to be in a “Resources” folder under Assets in the Project tab. I had to create a fodler called Resources and move my sprites their for this code to work.